1. Overview
1.概述
In this quick tutorial, we’ll write a List of Strings into a text file in Java in different ways. First, we’ll discuss FileWriter, then BufferedWriter, and finally, Files.writeString.
在这个快速教程中,我们将以不同的方式将List的字符串写入Java中的文本文件。首先,我们将讨论FileWriter,然后是BufferedWriter,最后是Files.writeString。
2. Using FileWriter
2.使用FileWriter
The java.io package contains a FileWriter class that we can use to write character data to a file. If we look at the hierarchy, we’ll see that the FileWriter class extends the OutputStreamWriter class, which in turn extends the Writer class.
java.io包包含一个FileWriter类,我们可以用它来向文件写入字符数据。如果我们看一下层次结构,我们会发现FileWriter类扩展了OutputStreamWriter类,后者又扩展了Writer类。
Let’s have a look at the constructors available to initialize a FileWriter:
让我们看一下用于初始化FileWriter的构造函数。
FileWriter f = new FileWriter(File file);
FileWriter f = new FileWriter(File file, boolean append);
FileWriter f = new FileWriter(FileDescriptor fd);
FileWriter f = new FileWriter(File file, Charset charset);
FileWriter f = new FileWriter(File file, Charset charset, boolean append);
FileWriter f = new FileWriter(String fileName);
FileWriter f = new FileWriter(String fileName, Boolean append);
FileWriter f = new FileWriter(String fileName, Charset charset);
FileWriter f = new FileWriter(String fileName, Charset charset, boolean append);
Note that all the constructors of the FileWriter class assume that the default byte-buffer size and the default character encoding are acceptable.
请注意,FileWriter类的所有构造函数都假定默认的字节缓冲区大小和默认的字符编码是可以接受的。
Now, let’s learn how to write a List of Strings into a text file using FileWriter:
现在,让我们学习如何使用FileWriter将List的字符串写进一个文本文件。
FileWriter fileWriter = new FileWriter(TEXT_FILENAME);
for (String str : stringList) {
fileWriter.write(str + System.lineSeparator());
}
fileWriter.close();
return TEXT_FILENAME;
One important thing to note in the example is that the FileWriter creates the sampleTextFile.txt if it isn’t present already. If the file exists, then we can overwrite it or append it depending on the choice of the constructor.
在这个例子中需要注意的一件事是,FileWriter创建了sampleTextFile.txt,如果它还没有存在的话。如果该文件存在,那么我们可以覆盖它或追加它,这取决于构造函数的选择。
3. Using BufferedWriter
3.使用BufferedWriter
The java.io package contains a BufferedWriter class that can be used with other Writers to write character data with better performance. But how is it more efficient?
java.io包包含一个BufferedWriter类,可以与其他Writer一起使用,以更好的性能写入字符数据。但它是如何做到更高效的呢?
When we use BufferedWriter, the characters are written to the buffer instead of the disk. When the buffer gets filled, all the data is written to the disk in one go, resulting in reduced traffic from/to the disk, and hence, contributing to better performance.
当我们使用BufferedWriter时,字符被写到缓冲区而不是磁盘上。当缓冲区被填满时,所有的数据被一次性写入磁盘,从而减少了磁盘的流量,因此,有助于提高性能。
If we talk about the hierarchy, the BufferedWriter class extends the Writer class.
如果我们谈及层次结构,BufferedWriter类扩展了Writer类。
Let’s have a look at the constructors available to initialize a BufferedWriter:
让我们看一下用于初始化BufferedWriter的构造函数。
BufferedWriter b = new BufferedWriter(Writer w);
BufferedWriter b = new BufferedWriter(Writer w, int size);
Note that it takes the default value if we don’t specify the buffer size.
请注意,如果我们不指定缓冲区的大小,它采用默认值。
Now, let’s explore how to write a List of Strings into a text file using BufferedWriter:
现在,让我们探讨一下如何使用BufferedWriter将List的字符串写进一个文本文件。
BufferedWriter br = new BufferedWriter(new FileWriter(TEXT_FILENAME));
for (String str : stringList) {
br.write(str + System.lineSeparator());
}
br.close();
return TEXT_FILENAME;
In the above code, we’ve wrapped FileWriter with BufferedWriter, which results in reducing read calls and, in turn, improving performance.
在上面的代码中,我们用BufferedWriter包装了FileWriter,从而减少了读取调用,进而提高了性能。
3. Using Files.writeString
3.使用Files.writeString
The java.nio package contains a method writeString() from the Files class to write characters into a file. This method was introduced in Java 11.
java.nio包包含一个来自Files类的writeString()方法,用于将字符写入文件中。这个方法是在Java 11中引入的。
Let’s have a look at the two overloaded methods available in java.nio.file.Files:
让我们看一下java.nio.file.Files中的两个重载方法。
public static Path writeString(Path path, CharSequence csq, OpenOption… options) throws IOException
public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption… options) throws IOException
Note that in the first method, we don’t have to specify the Charset. By default, it takes UTF-8 Charset, whereas in the second method, we can specify the Charset. Finally, let’s learn how to write a List of Strings into a text file using Files.writeString:
请注意,在第一个方法中,我们不需要指定Charset。默认情况下,它采用UTF-8 Charset,而在第二个方法中,我们可以指定Charset。最后,让我们学习如何使用Files.writeString将一个List的字符串写入一个文本文件。
Path filePath = Paths.get(TEXT_FILENAME);
Files.deleteIfExists(filePath);
Files.createFile(filePath);
for (String str : stringList) {
Files.writeString(filePath, str + System.lineSeparator(),
StandardOpenOption.APPEND);
}
return filePath.toString();
In the example above, we deleted the file if it already existed and then created a file using Files.createFile method. Note that we have set OpenOption field to StandardOperation.APPEND, which means the file will open in append mode. If we don’t specify OpenOption, then we can expect two things to happen:
在上面的例子中,如果文件已经存在,我们删除了它,然后使用Files.createFile方法创建了一个文件。注意,我们已经将OpenOption字段设置为StandardOperation.APPEND,,这意味着文件将以追加模式打开。如果我们不指定OpenOption,,那么我们可以期待两件事发生。
- The file will be overwritten if it’s already present
- File.writeString will create a new file and write on it if the file doesn’t exist
4. Testing
4.测试
For JUnit tests, let’s define a List of Strings:
对于JUnit测试,让我们定义一个List的Strings。
private static final List<String> stringList = Arrays.asList("Hello", "World");
Here, we’ll find out the count of lines of the output file using the NIO Files.lines and count(). The count should be equal to the number of Strings in the List.
这里,我们将使用NIO Files.lines和count()找出输出文件的行数。这个计数应该等于List中的Strings的数量。
Now, let’s head to testing of our FileWriter implementation:
现在,让我们开始测试我们的FileWriter实现。
@Test
public void givenUsingFileWriter_whenStringList_thenGetTextFile() throws IOException {
String fileName = FileWriterExample.generateFileFromStringList(stringList);
long count = Files.lines(Paths.get(fileName)).count();
assertTrue("No. of lines in file should be equal to no. of Strings in List", ((int) count) == stringList.size());
}
Next, we’ll test the BufferedWriter implementation:
接下来,我们将测试BufferedWriter的实现。
@Test
public void givenUsingBufferedWriter_whenStringList_thenGetTextFile() throws IOException {
String fileName = BufferedWriterExample.generateFileFromStringList(stringList);
long count = Files.lines(Paths.get(fileName)).count();
assertTrue("No. of lines in file should be equal to no. of Strings in List", ((int) count) == stringList.size());
}
Finally, let’s test our Files.writeString implementation:
最后,让我们测试一下我们的Files.writeString实现。
@Test
public void givenUsingFileWriteString_whenStringList_thenGetTextFile() throws IOException {
String fileName = FileWriteStringExample.generateFileFromStringList(stringList);
long count = Files.lines(Paths.get(fileName)).count();
assertTrue("No. of lines in file should be equal to no. of Strings in List", ((int) count) == stringList.size());
}
5. Conclusion
5.总结
In this article, we explored three common ways of writing a List of Strings into a text file. Also, we tested our implementation by writing JUnit tests.
在这篇文章中,我们探讨了将List of Strings写入文本文件的三种常见方法。同时,我们通过编写JUnit测试来测试我们的实现。
As always, the complete code for the tutorial is available over on GitHub.
一如既往,该教程的完整代码可在GitHub上获取。