IO流(1)创建文件
文件流:文件在程序中是以流的形式来操作的。
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
创建文件
- new File(String pathname)//根据路径构造一个File对象
- new File(File parent,String child)//根据父目录文件+子目录构建
- new File(String parent,String child)//根据父目录+子路径构建
createNewFile 创建新文件
@Test //方式1:new File(String pathname) public void create01(){ String filePath="e:\\news1.txt"; File file = new File(filePath); //File file = new File("e:\\news1.txt"); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } } @Test //方式2:new File(File parent,String child)//根据父目录文件+子路径构建 //e:\\news2.txt public void create02(){ File parentFile = new File("e:\\");//父 String fileName = "news2.txt";//子 File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } } @Test //方式3:new File(String parent,String child)//根据父目录+子路径构建 public void create03(){ File parentPath = new File("e:\\"); String fileName = "names3.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } }
获取文件信息
package IO; import java.io.File; public class Test { public static void main(String[] args) { } //获取文件信息 @org.junit.Test public void information(){ File file = new File("e:\\news1.txt"); //调用相印的方法,得到对应的信息 System.out.println("文件名字:"+file.getName()); System.out.println("文件绝对路径:"+file.getAbsolutePath()); System.out.println("文件父级目录:"+file.getParent()); System.out.println("文件大小(字节):"+file.length());//一个字母占一个字节,中文占3个 System.out.println("文件是否存在:"+file.exists());//T System.out.println("是不是一个文件:"+file.isFile());//T System.out.println("是不是一个目录:"+file.isDirectory());//F } }
创建一级目录使用mkdir();,创建多级目录使用mkdirs();
//判断f:\\demo\\a\\b\\c目录是否存在,不存在就创建 @Test public void m3(){ String directoryPath = "f:\\demo\\a\\b\\c"; File file = new File(directoryPath); if (file.exists()){ System.out.println(directoryPath+"存在"); }else{ if(file.mkdirs()){//创建一级目录使用mkdir();,创建多级目录使用mkdirs(); System.out.println(directoryPath+"创建成功"); }else{ System.out.println("创建失败"); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端