上QQ阅读APP看书,第一时间看更新
Writing ouput data
After the data is read and processed, we often want to put it back on disk. For text, this is usually done using the Writer objects.
Suppose we read the sentences from text.txt and we need to convert each line to uppercase and write them back to a new file output.txt; the most convenient way of writing the text data is via the PrintWriter class:
try (PrintWriter writer = new PrintWriter("output.txt", "UTF-8")) {
for (String line : lines) {
String upperCase = line.toUpperCase(Locale.US);
writer.println(upperCase);
}
}
In Java NIO API, it would look like this:
Path output = Paths.get("output.txt");
try (BufferedWriter writer = Files.newBufferedWriter(output,
StandardCharsets.UTF_8)) {
for (String line : lines) {
String upperCase = line.toUpperCase(Locale.US);
writer.write(upperCase);
writer.newLine();
}
}
Both ways are correct and you should select the one that you prefer. However, it is important to remember to always include the encoding; otherwise, it may use some default values which are platform-dependent and sometimes arbitrary.