Java文件读写主要有四种方式:1. FileReader/FileWriter用于文本文件,结合BufferedReader/BufferedWriter提升效率;2. FileInputStream/FileOutputStream适用于所有文件类型,按字节操作,适合处理图片、音频等二进制数据;3. NIO的Files类提供简洁API,推荐用于现代Java开发中的简单读写,如readAllLines和write方法;4. Scanner和PrintWriter适合格式化输入输出,Scanner可解析文本数据,PrintWriter便于生成可读日志。选择依据包括数据类型、文件大小及性能需求,建议优先使用try-with-resources确保资源自动释放。

Java 中读取和写入文件主要通过 java.io 和 java.nio 包中的类来实现。下面详细介绍常见的文件读写方式、适用场景以及具体操作步骤。
适用于读写文本文件,按字符处理,自动处理编码问题(默认平台编码)。
读取文件示例:FileReader 用于读取字符文件。使用 BufferedReader 可提高读取效率。
try (FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
FileWriter 用于写入字符文件。使用 BufferedWriter 提升性能。
try (FileWriter fw = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Hello, Java File IO!");
bw.newLine(); // 换行
bw.write("第二行内容");
} catch (IOException e) {
e.printStackTrace();
}
适用于所有类型文件(如图片、音频、视频等),以字节为单位操作。
读取二进制文件示例:
try (FileInputStream fis = new FileInputStream("image.jpg")) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
// 处理数据,例如写入另一个文件或网络传输
System.out.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
try (FileOutputStream fos = new FileOutputStream("copy.jpg")) {
byte[] data = ...; // 要写入的数据
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
}
Java 7 引入的 NIO.2 提供了更简洁的 API,适合简单读写操作。
立即学习“Java免费学习笔记(深入)”;
读取整个文件内容:
Path path = Paths.get("data.txt");
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
List<String> content = Arrays.asList("第一行", "第二行", "第三行");
Path path = Paths.get("output.txt");
try {
Files.write(path, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
适合从文件读取格式化数据或向文件输出可读内容。
用 Scanner 读取文本:
try (Scanner scanner = new Scanner(Paths.get("input.txt"), "UTF-8")) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}
try (PrintWriter pw = new PrintWriter(new FileWriter("log.txt"))) {
pw.println("程序启动时间: " + new Date());
pw.printf("用户 %s 登录%n", "zhangsan");
} catch (IOException e) {
e.printStackTrace();
}
基本上就这些常用方式。选择哪种方法取决于你的需求:处理文本还是二进制数据、文件大小、是否需要高性能或简洁代码。NIO 的 Files 工具类适合大多数简单场景,而传统流更适合大文件或复杂控制。注意始终使用 try-with-resources 自动关闭资源,避免内存泄漏。
以上就是java怎么读取和写入文件 文件读写操作的详细实现步骤的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号