Java File 核心知识点

Java File 核心知识点

一、核心类

  • java.io.File:文件 / 目录路径描述类,可判断属性、创建删除,不能读写内容
  • 字节流:FileInputStream/FileOutputStream 处理所有类型文件
  • 字符流:FileReader/FileWriter 仅处理文本文件

二、File 类常用构造

java

运行

复制代码
File file = new File("a.txt"); //相对路径
File file = new File("D:\\test\\a.txt"); //绝对路径

三、File 常用方法

判断方法

  • exists():文件是否存在
  • isFile():是否为文件
  • isDirectory():是否为文件夹

创建删除

  • createNewFile():新建空文件
  • mkdir():创建单级目录
  • mkdirs():创建多级目录
  • delete():删除文件 / 空目录

获取信息

  • getName():文件名
  • getAbsolutePath():绝对路径
  • length():文件字节大小

四、文件读写基础

1. 字节流读写

java

运行

复制代码
//写入
try(FileOutputStream fos = new FileOutputStream("b.txt")){
    fos.write("测试内容".getBytes());
}catch (IOException e){
    e.printStackTrace();
}

//读取
try(FileInputStream fis = new FileInputStream("b.txt")){
    byte[] buf = new byte[1024];
    int len;
    while((len = fis.read(buf)) != -1){
        System.out.print(new String(buf,0,len));
    }
}catch (IOException e){
    e.printStackTrace();
}

2. 字符流读写(文本专用)

java

运行

复制代码
//写入
try(FileWriter fw = new FileWriter("c.txt",true)){//true追加
    fw.write("文字内容");
}catch (IOException e){}

//读取
try(FileReader fr = new FileReader("c.txt")){
    char[] ch = new char[1024];
    int len;
    while((len = fr.read(ch))!=-1){
        System.out.print(new String(ch,0,len));
    }
}catch (IOException e){}

五、关键要点

  1. 路径分隔:Windows 用\\,通用写法/
  2. 流用完必须关闭,try-with-resources自动关流
  3. write覆盖原有内容,构造传true开启追加
  4. 字节流通用,字符流只适配 txt 等文本
  5. 所有 IO 操作必须捕获IOException异常

六、常用遍历目录

java

运行

复制代码
File dir = new File("D:\\test");
File[] files = dir.listFiles();
for(File f : files){
    System.out.println(f.getName());
}
相关推荐
NE_STOP14 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园15 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆15 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz15 小时前
Maven依赖冲突
java·服务器·maven
swordbob15 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯16 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网16 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠16 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
源分享16 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Flittly16 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring