Java IO 必知必会:File 类与字节流实战
2026/6/8 14:06:50 网站建设 项目流程

一、File 类 —— 文件路径与属性操作

File不读写内容,只负责路径表示和文件/目录管理

创建与常用方法

File file = new File("data.txt"); File dir = new File("C:/test"); // 最常用的方法 file.exists(); // 是否存在 file.isFile(); // 是否为文件 file.isDirectory(); // 是否为目录 file.getName(); // 文件名 file.getAbsolutePath(); // 绝对路径 file.length(); // 文件大小(字节) file.createNewFile(); // 创建文件 file.mkdirs(); // 递归创建目录 file.delete(); // 删除 file.listFiles(); // 列出目录内容

遍历目录示例

File dir = new File("."); File[] files = dir.listFiles(); for (File f : files) { System.out.println((f.isDirectory() ? "[DIR] " : "[FILE] ") + f.getName()); }

二、InputStream —— 读字节

核心方法

int read() // 读一个字节,返回 0~255,结尾返回 -1 int read(byte[] b) // 读一批字节到数组,返回实际读取长度 void close()

正确写法(带缓冲,推荐)

try (FileInputStream fis = new FileInputStream("data.txt")) { byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) != -1) { System.out.write(buf, 0, len); // 不要用 println,会乱码 } }

三、OutputStream —— 写字节

核心方法

void write(int b) // 写一个字节(低8位) void write(byte[] b) // 写整个数组 void write(byte[] b, int off, int len) // 写数组的指定部分

覆盖写入 vs 追加写入

// 覆盖写入(默认) try (FileOutputStream fos = new FileOutputStream("out.txt")) { fos.write("Hello".getBytes()); } // 追加写入(第二个参数传 true) try (FileOutputStream fos = new FileOutputStream("out.txt", true)) { fos.write("World".getBytes()); }

四、Buffered 流 —— 性能关键

直接读写大文件很慢,加 Buffered 包装可提升 10x 以上性能


五、文件拷贝完整代码

把前面所有知识点串起来,这是最实用的代码:

public static void copy(String src, String dst) throws IOException { try (InputStream in = new BufferedInputStream(new FileInputStream(src)); OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) { byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } }

六、try-with-resources 一句话解释

new XXX()写在try()括号里,Java 自动帮你关流,不用手写finally

// ✅ 推荐:自动关流 try (FileInputStream fis = new FileInputStream("a.txt")) { // 使用 fis } // ❌ 不推荐:手动关流,代码冗长且容易漏 FileInputStream fis = null; try { fis = new FileInputStream("a.txt"); } finally { if (fis != null) fis.close(); }

七、核心要点速记

要点说明
File不读写只管路径、属性、目录操作
try-with-resources自动关流,标准写法
Buffered包装大文件必备,性能提升显著
追加模式new FileOutputStream(path, true)
文本编码getBytes("UTF-8")明确指定

如有疑问欢迎留言交流

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询