Java FileWriter 类
最后修改时间:2025 年 4 月 16 日
java.io.FileWriter
类是一个用于写入字符文件的便捷类。它扩展了 OutputStreamWriter
并内部创建了必要的 FileOutputStream
。FileWriter 使用默认的字符编码和缓冲区大小。
FileWriter
旨在将字符流写入文件。它通常用于文本文件操作。该类自动处理字符到字节的转换。为了获得更好的性能,请将其包装在 BufferedWriter 中。
FileWriter 类概述
FileWriter
提供了几个构造函数,用于不同的文件写入场景。它可以附加到现有文件或覆盖它们。该类对于文件访问错误会抛出 IOException
。所有写入操作默认都会被缓冲。
public class FileWriter extends OutputStreamWriter { public FileWriter(String fileName) throws IOException; public FileWriter(String fileName, boolean append) throws IOException; public FileWriter(File file) throws IOException; public FileWriter(File file, boolean append) throws IOException; public FileWriter(FileDescriptor fd); public void write(int c) throws IOException; public void write(char[] cbuf) throws IOException; public void write(char[] cbuf, int off, int len) throws IOException; public void write(String str) throws IOException; public void write(String str, int off, int len) throws IOException; public void flush() throws IOException; public void close() throws IOException; }
上面的代码显示了 FileWriter
提供的关键方法。这些方法允许将字符和字符串写入文件。构造函数中的 append 参数控制是覆盖还是附加到现有文件。
创建 FileWriter
FileWriter 可以使用文件路径字符串、File 对象或 FileDescriptor 创建。最简单的构造函数只接受一个文件名。如果文件无法打开,所有构造函数都可能抛出 IOException。
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try { // Create with file path (overwrites existing) FileWriter writer1 = new FileWriter("output.txt"); // Create with append mode FileWriter writer2 = new FileWriter("log.txt", true); // Create with File object java.io.File file = new java.io.File("data.txt"); FileWriter writer3 = new FileWriter(file); System.out.println("FileWriter instances created successfully"); writer1.close(); writer2.close(); writer3.close(); } catch (IOException e) { e.printStackTrace(); } } }
此示例演示了创建 FileWriter 实例的不同方法。第一个写入器会覆盖现有文件。第二个附加到文件。完成后始终关闭写入器,以确保所有数据都被写入并释放资源。
将字符写入文件
FileWriter 提供了几种用于字符数据写入的方法。最简单的方法是写入单个字符。也可以写入字符数组和字符串。所有写入操作都会被缓冲以提高效率。
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try (FileWriter writer = new FileWriter("characters.txt")) { // Write single character writer.write('A'); // Write character array char[] chars = {'B', 'C', 'D'}; writer.write(chars); // Write portion of character array char[] moreChars = {'E', 'F', 'G', 'H', 'I'}; writer.write(moreChars, 1, 3); // Writes F, G, H System.out.println("Characters written successfully"); } catch (IOException e) { e.printStackTrace(); } } }
此示例显示了不同的字符写入方法。try-with-resources 语句确保正确关闭写入器。字符数组可以完全或部分写入。在调用 flush() 或 close() 之前,数据可能会保留在缓冲区中。
将字符串写入文件
FileWriter 提供了方便的字符串写入方法。可以写入整个字符串或子字符串。字符串写入非常有效,因为它避免了手动字符数组转换。需要时应显式添加换行符。
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try (FileWriter writer = new FileWriter("strings.txt")) { // Write complete string writer.write("Hello, World!\n"); // Write portion of string String message = "Java FileWriter Example"; writer.write(message, 5, 10); // Writes "FileWriter" // Multiple writes writer.write("\n"); writer.write("Line 1\nLine 2\nLine 3"); System.out.println("Strings written successfully"); } catch (IOException e) { e.printStackTrace(); } } }
此示例演示了字符串写入操作。第一个写入操作输出一个带有换行符的完整字符串。第二个写入操作写入一个子字符串。多个写入操作在输出文件中合并。请记住,换行符是与平台相关的。
附加到现有文件
FileWriter 可以附加到现有文件,而不是覆盖它们。这对于日志文件和数据收集很有用。append 模式在构造函数中指定。附加时会保留现有内容。
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try { // First create a file with initial content FileWriter writer1 = new FileWriter("log.txt"); writer1.write("=== Application Log ===\n"); writer1.write("Startup completed\n"); writer1.close(); // Now append to the file FileWriter writer2 = new FileWriter("log.txt", true); writer2.write("User logged in at " + new java.util.Date() + "\n"); writer2.write("Data processing started\n"); writer2.close(); System.out.println("Log entries appended successfully"); } catch (IOException e) { e.printStackTrace(); } } }
此示例显示了如何附加到现有文件。第一个写入器使用初始内容创建文件。第二个写入器以附加模式打开并添加新条目。布尔值 true 参数在构造函数中启用附加模式。
刷新和关闭写入器
FileWriter 缓冲写入以提高效率。flush 方法强制立即写入缓冲数据。close 方法刷新并释放资源。始终关闭写入器以防止资源泄漏。
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { FileWriter writer = null; try { writer = new FileWriter("important.txt"); // Write critical data writer.write("Critical System Data\n"); writer.write("Version: 2.5.1\n"); // Ensure data is written immediately writer.flush(); System.out.println("Data flushed to disk"); // Write more data writer.write("Last updated: " + new java.util.Date() + "\n"); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); System.out.println("Writer closed successfully"); } catch (IOException e) { e.printStackTrace(); } } } } }
此示例演示了使用 flush 和 close 的正确资源管理。flush 调用确保关键数据立即被写入。finally 块保证写入器被关闭。在 Java 7+ 中,try-with-resources 是自动关闭的首选方法。
将 FileWriter 与 BufferedWriter 一起使用
为了提高具有许多小写入操作的性能,请将 FileWriter 包装在 BufferedWriter 中。这增加了另一个缓冲层,减少了系统调用。BufferedWriter 提供了额外的功能,如 newLine()。
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try (BufferedWriter writer = new BufferedWriter( new FileWriter("buffered.txt"))) { // Write lines efficiently for (int i = 1; i <= 10; i++) { writer.write("Line " + i); writer.newLine(); // Platform-independent newline } // Write large text writer.write("This is a longer piece of text that will benefit "); writer.write("from buffering as it reduces the number of system "); writer.write("calls needed to write all this data to the file."); System.out.println("Data written with buffering"); } catch (IOException e) { e.printStackTrace(); } } }
此示例显示了包装在 BufferedWriter 中的 FileWriter。newLine 方法提供与平台无关的行尾。缓冲可以提高许多小写入的性能。try-with-resources 适当地处理关闭这两个写入器。
来源
在本文中,我们介绍了 Java FileWriter 类的基本方法和特性。理解这些概念对于在 Java 应用程序中处理文本文件输出至关重要。
作者
列出所有Java教程。