FileInputStream 和 FileOutputStream 简介
FileInputStream 和 FileOutputStream 是 Java 中用于读写文件的字节流类,属于 java.io
包。FileInputStream 用于从文件中读取字节数据,FileOutputStream 用于将字节数据写入文件。两者适用于二进制文件(如图片、音频等)或文本文件的底层操作。
FileInputStream 使用方法
创建 FileInputStream
通过文件路径或 File 对象创建 FileInputStream:
FileInputStream fis = new FileInputStream("example.txt"); // 通过文件路径
// 或
File file = new File("example.txt");
FileInputStream fis = new FileInputStream(file); // 通过 File 对象
读取文件数据
使用 read()
方法逐字节读取,返回 -1 表示文件结束:
int data;
while ((data = fis.read()) != -1) {System.out.print((char) data); // 转换为字符输出
}
批量读取
通过字节数组提高读取效率:
byte[] buffer = new byte[1024]; // 缓冲区大小
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {String content = new String(buffer, 0, bytesRead); // 转换为字符串System.out.print(content);
}
关闭流
使用完成后必须关闭流以释放资源:
fis.close();
使用 try-with-resources 自动关闭
推荐使用 try-with-resources 语法,避免手动关闭:
try (FileInputStream fis = new FileInputStream("example.txt")) {// 读取操作
} catch (IOException e) {e.printStackTrace();
}
FileOutputStream 使用方法
创建 FileOutputStream
通过文件路径或 File 对象创建,可指定是否追加模式:
FileOutputStream fos = new FileOutputStream("output.txt"); // 覆盖模式
// 或追加模式
FileOutputStream fos = new FileOutputStream("output.txt", true);
写入数据
使用 write()
方法写入单个字节或字节数组:
// 写入单个字节
fos.write('A'); // 写入字节数组
byte[] data = "Hello, World!".getBytes();
fos.write(data);
批量写入
通过字节数组批量写入:
String content = "Hello, Java!";
byte[] bytes = content.getBytes();
fos.write(bytes, 0, bytes.length); // 指定偏移量和长度
关闭流
写入完成后关闭流:
fos.close();
使用 try-with-resources 自动关闭
try (FileOutputStream fos = new FileOutputStream("output.txt")) {fos.write("Hello".getBytes());
} catch (IOException e) {e.printStackTrace();
}
综合示例:文件复制
结合 FileInputStream 和 FileOutputStream 实现文件复制:
try (FileInputStream fis = new FileInputStream("source.txt");FileOutputStream fos = new FileOutputStream("target.txt")) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = fis.read(buffer)) != -1) {fos.write(buffer, 0, bytesRead);}
} catch (IOException e) {e.printStackTrace();
}
注意事项
- 异常处理:必须处理
IOException
,如文件不存在或无权限访问。 - 资源释放:确保流被关闭,推荐使用 try-with-resources。
- 性能优化:使用缓冲区(字节数组)减少 IO 操作次数。
- 字符编码:直接处理字节时需注意字符编码问题,文本文件建议使用字符流(如
FileReader
/FileWriter
)。
常见问题
如何读取大文件?
分块读取并处理,避免内存溢出:
byte[] buffer = new byte[8192]; // 8KB 缓冲区
while ((bytesRead = fis.read(buffer)) != -1) {// 处理每一块数据
}
如何追加内容到文件?
创建 FileOutputStream 时设置 append
参数为 true
:
FileOutputStream fos = new FileOutputStream("log.txt", true);