IO流(1)
IO流(1)
文件
-
文件流
文件在程序中以流的形式来操作
-
输入流:数据从数据源(文件)到程序(内存)的路径
-
输出流:数据从程序(内存)到数据源(文件)的路径
创建文件
//方法1:new File(String pathname) 根据路径构建一个File对象
public void create1(){
String filepath = "d:\\news1.txt";
File file= new File(filepath);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建失败");
}
}
//方法2:new File(File parent,String child) 根据父目录文件+子路径构建
public void create2(){
File file = new File("d:\\");
String fileNmae ="news2.txt";
File file1 = new File(file, fileNmae);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
//方法3:new File(String parent,String child) 根据父目录+子路径构建
public void cteate3(){
String parentPath="d:\\";
String filepath = "news1.txt";
File file = new File(parentPath,filepath);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
获取文件信息
常用方法:
//获取文件信息
public void info(){
//创建文件对象
File file = new File("d:\\news1.txt");
//调用方法
System.out.println("文件名"+file.getName());
System.out.println("文件绝对路径"+file.getAbsolutePath());
System.out.println("文件父目录"+file.getParent());
System.out.println("文件大小"+file.length());
System.out.println("文件是否存在"+file.exists());
System.out.println("是不是一个文件"+file.isFile());
System.out.println("是不是一个目录"+file.isDirectory());
目录的操作和文件删除
-
mkdir 创建一级目录
public void m1(){ String directorPath="d:\\hmy"; File file=new File(directorPath); if(file.exists()){ System.out.println(directorPath+"存在--"); }else { if (file.mkdir()){ System.out.println(directorPath+"创建成功--"); }else { System.out.println(directorPath+"创建失败--"); } } }
-
mkdirs 创建多级目录
public void m2(){ String directorPath="d:\\hmy\\a"; File file=new File(directorPath); if(file.exists()){ System.out.println(directorPath+"存在--"); }else { if (file.mkdirs()){ System.out.println(directorPath+"创建成功--"); }else { System.out.println(directorPath+"创建失败--"); } } }
-
delete 删除空目录或文件
public void m3(){ String filePath="d:\\news1.txt"; File file=new File(filePath); if(file.exists()){ if (file.delete()){ System.out.println(filePath+"删除成功--"); }else { System.out.println(filePath+"删除失败--"); } }else { System.out.println("不存在"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!