July 2017
Beginner to intermediate
715 pages
17h 3m
English
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) { ...