PrintWriter vs. FileWriter in Java – Java 中的 PrintWriter 与 FileWriter

最后修改: 2023年 10月 30日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The Java standard library provides API for file manipulation. The PrintWriter and FileWriter classes help to write characters to a file. However, the two classes are intended for different use cases.

Java 标准库提供了用于文件操作的 API。PrintWriterFileWriter 类有助于将字符写入文件。但是,这两个类的用途不同。

In this tutorial, we’ll explore details about PrintWriter and FileWriter with respect to their use cases. Also, we’ll see the differences and similarities between the two classes.

在本教程中,我们将详细介绍 PrintWriterFileWriter 的用例。此外,我们还将了解这两个类之间的异同。

2. PrintWriter

2.打印写入器</em

The PrintWriter class helps write formatted text to an output stream like file and console.

PrintWriter类有助于将格式化文本写入文件和控制台等输出流

Moreover, methods in the PrintWriter class don’t throw IOExceptions. Instead, it has the checkError() method to know the state of the write operation. The checkError() method returns false if the write operation passes, and true if it failed due to an error.

此外,PrintWriter 类中的方法不会抛出 IOExceptions 异常。相反,它使用 checkError() 方法来了解写操作的状态。如果写操作通过,checkError() 方法返回 false;如果写操作因错误而失败,返回 true。

Additionally, the checkError() flushes the stream if it’s not closed before checking the error state.

此外,checkError() 在检查错误状态之前,如果流没有关闭,则会刷新流。

Furthermore, PrintWriter provides a method named flush() to explicitly flush the stream after write operations. However, when used with the try-with-resources block, there’s no need to explicitly flush the stream.

此外,PrintWriter提供了一个名为flush() 的方法,用于在写操作后显式地刷新流。但是,当与 try-with-resources 块一起使用时,无需显式地刷新流。

2.1. PrintWriter.println()

2.1.PrintWriter.println()

The println() method writes a string to the output stream and terminates with a new line. It can’t write formatted text to an output stream.

println()方法将字符串写入输出流,并以新行结束。该方法不能将格式化文本写入输出流。

Also, PrintWriter provides the print() method in case we decide not to terminate a string with a new line.

此外,PrintWriter还提供了print() 方法,以防我们决定不以换行结束字符串。

Here’s an example using the println() method to write a string to a file:

下面是一个使用 println() 方法将字符串写入文件的示例:

@Test
void whenWritingToTextFileUsingPrintWriterPrintln_thenTextMatches() throws IOException {
    String result = "I'm going to Alabama\nAlabama is a state in the US\n";
    try (PrintWriter pw = new PrintWriter("alabama.txt");) {
        pw.println("I'm going to Alabama");
        pw.println("Alabama is a state in the US");
    }
    Path path = Paths.get("alabama.txt");
    String actualData = new String(Files.readAllBytes(path));
    assertEquals(result, actualData);
}

Here, we create a PrintWriter object which takes the file path as an argument. Next, we invoke the println() method on the PrintWriter object to write characters to the file.

在这里,我们创建了一个 PrintWriter 对象,它将文件路径作为参数。接下来,我们调用 PrintWriter 对象上的 println() 方法,将字符写入文件。

Finally, we assert that the expected result is equal to the file content.

最后,我们断言预期结果等于文件内容。

Notably, PrintWriter also provides a write() method to write text to file, and we can use it in place of the print() method.

值得注意的是,PrintWriter 还提供了一个用于将文本写入文件的 write() 方法,我们可以用它来代替 print() 方法

2.2. PrintWriter.printf()

2.2.PrintWriter.printf()

The printf() method helps to write a formatted text to an output stream. We can use format specifiers like %s, %d, .2f, etc. to write different data types to an output stream.

printf()方法有助于将格式化文本写入输出流。我们可以使用 格式指定符,如 %s%d.2f 等,将不同的数据类型写入输出流。

Let’s see some sample code using printf() to write formatted data to a file:

让我们看看使用 printf() 向文件写入格式化数据的示例代码:

@Test
void whenWritingToTextFileUsingPrintWriterPrintf_thenTextMatches() throws IOException {
    String result = "Dreams from My Father by Barack Obama";
    File file = new File("dream.txt");
    try (PrintWriter pw = new PrintWriter(file);) {
        String author = "Barack Obama";
        pw.printf("Dreams from My Father by %s", author);
        assertTrue(!pw.checkError());
    }
    try (BufferedReader reader = new BufferedReader(new FileReader(file));) {
        String actualData = reader.readLine();
        assertEquals(result, actualData);
    }
}

In the code above, we write formatted text to a file. We use the %s identifier to directly add a String data type to the text.

在上面的代码中,我们将格式化文本写入文件。我们使用 %s 标识符直接为文本添加 String 数据类型。

Also, we create an instance of BufferedReader that takes the FileReader object as an argument to read the content of a file.

此外,我们还创建了一个 BufferedReader 的实例,该实例将 FileReader 对象作为参数,用于读取文件内容。

Since the method doesn’t throw an IOException, we invoke the checkError() method to know the state of the write operation. In this case, checkError() returns false, indicating no errors.

由于该方法不会抛出 IOException 异常,因此我们调用 checkError() 方法来了解写操作的状态。在这种情况下,checkError() 返回 false, 表示没有错误。

3. FileWriter

3.文件写入器</em

The FileWriter class extends the Writer class. It provides a convenient method to write characters to a file using a preset buffer size.

FileWriter 类扩展了 Writer 类。它提供了一种方便的方法,使用预设的缓冲区大小将字符写入文件

FileWriter doesn’t flush the buffer automatically. We need to invoke the flush() method. However, when FileWriter is used with the try-with-resources block, it automatically flushes and closes the stream when exiting the block.

FileWriter 不会自动刷新缓冲区。我们需要调用 flush() 方法。但是,当 FileWriter try-with-resources 块一起使用时,它会在退出块时自动刷新并关闭流。

Furthermore, it throws an IOException in the case of a missing file, when a file cannot be opened, etc.

此外,在文件丢失、文件无法打开等情况下,它会抛出 IOException 异常

Unlike PrintWriter, it can’t write formatted text to a file.

PrintWriter 不同,它不能将格式化文本写入文件。

Let’s see an example using the write() method in FileWriter class to write characters to a File:

让我们来看一个使用 FileWriter 类中的 write() 方法向 File 中写入字符的示例:

@Test
void whenWritingToTextFileUsingFileWriter_thenTextMatches() throws IOException {
    String result = "Harry Potter and the Chamber of Secrets";
    File file = new File("potter.txt");
    try (FileWriter fw = new FileWriter(file);) {
        fw.write("Harry Potter and the Chamber of Secrets");
    }
    try (BufferedReader reader = new BufferedReader(new FileReader(file));) {
        String actualData = reader.readLine();
        assertEquals(result, actualData);
    }
}

In the code above, we create an instance of a File and pass it to a FileWriter object. Next, we invoke the write() method on the FileWriter object to write a string of characters to a file.

在上面的代码中,我们创建了一个 File 实例,并将其传递给 FileWriter 对象。接下来,我们调用 FileWriter 对象上的 write() 方法,将字符串写入文件。

Finally, we assert that the expected result is equal to the content of the file.

最后,我们断言预期结果等于文件内容。

4. Conclusion

4.结论

In this article, we learned the basic usage of FileWriter and PrintWriter with example code.

在本文中,我们通过示例代码学习了 FileWriterPrintWriter 的基本用法。

The primary purpose of a FileWriter is to write characters to a file. However, PrintWriter has more functionalities. It can write to other output streams apart from a file. Also, it provides a method to write formatted text to a file or console.

FileWriter 的主要用途是将字符写入文件。然而,PrintWriter具有更多功能。除文件外,它还可以写入其他输出流。此外,它还提供了一种将格式化文本写入文件或控制台的方法。

As always, the source code for the examples is available over on GitHub.

与往常一样,这些示例的源代码可在 GitHub 上获取。