Reading and Writing Character Data
The Files class provides methods for reading and writing character data to files. These methods can be categorized as follows:
- Methods that create character I/O streams (BufferedReader, BufferedWriter) chained to a Path object that denotes a file. The methods of the buffered reader and writer can then be used to read and write characters to the file, respectively.
- Methods that directly use a Path object, and read and write characters to the file denoted by the Path object.
Reading and Writing Character Data Using Buffered I/O Streams
The newBufferedReader() and newBufferedWriter() methods of the Files class create buffered readers and writers, respectively, that are chained to a Path object denoting a file. Interoperability between character I/O streams in the java.io package can then be leveraged to chain appropriate I/O streams for reading and writing character data to a file (§20.3, p. 1241).
Previously we have used constructors of the BufferedReader class (§20.3, p. 1251) and the BufferedWriter class (§20.3, p. 1250) in the java.io package to instantiate buffered readers and writers that are chained to a Reader or a Writer, respectively. Using the methods of the Files class is the recommended practice for creating buffered readers and writers when dealing with text files.
static BufferedReader newBufferedReader(Path path) throws IOException
static BufferedReader newBufferedReader(Path path, Charset cs)
throws IOException
Opens the file denoted by the specified path for reading, and returns a BufferedReader of a default size to read text efficiently from the file, using either the UTF-8 charset or the specified charset to decode the bytes, respectively. Contrast these methods with the constructors of the java.io.BufferReader class (§20.3, p. 1251).
static BufferedWriter newBufferedWriter(Path path, OpenOption… options)
throws IOException
static BufferedWriter newBufferedWriter(Path path, Charset cs,
OpenOption… options) throws IOException
Opens or creates a file denoted by the specified path for writing, returning a BufferedWriter of a default size that can be used to write text efficiently to the file, using either the UTF-8 charset or the specified charset to encode the characters, respectively. See also constructors of the java.io.BufferWriter class (§20.3, p. 1250).
The code at (1) and at (3) in Example 21.2 illustrates writing lines to a text file using a buffered writer and reading lines from a text file using a buffered reader, respectively. The methods newBufferedWriter() and newBufferedReader() create the necessary buffered writer and reader at (2) and (4), respectively, whose methods are used to write and read the lines from the file.
Example 21.2 Reading and Writing Text Files
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class ReadingWritingTextFiles {
public static void main(String[] args) throws IOException {
// List of strings:
List<String> lines = List.of(“Guess who got caught?”, “Who?”,
“NullPointerException.”,
“Seriously?”, “No. Finally.”);
// Text file:
String filename = “project/linesOnly.txt”;
Path path = Path.of(filename);
// Writing lines using buffered writer: (1)
try (BufferedWriter writer = Files.newBufferedWriter(path)) { // (2)
for(String str : lines) {
writer.write(str); // Write a string.
writer.newLine(); // Terminate with a newline.
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Read lines using buffered reader: (3)
lines = new ArrayList<>();
try(BufferedReader reader= Files.newBufferedReader(path)) { // (4)
String line = null;
while ((line = reader.readLine()) != null) { // EOF when null is returned.
lines.add(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.printf(“Lines read from file \”%s\”:%n%s%n”, path, lines);
// Write the list of strings in one operation:
Files.write(path, lines); // (5)
// Write the joined lines in one operation:
String joinedLines = String.join(System.lineSeparator(), lines);
Files.writeString(path, joinedLines); // (6)
// Read all contents into a String, including line separators:
String allContent = Files.readString(path); // (7)
System.out.printf(“All lines read from file \”%s\”:%n%s%n”, path, allContent);
// Read all lines into a list of String:
lines = Files.readAllLines(path); // (8)
System.out.printf(“List of lines read from file \”%s\”:%n%s%n”, path, lines);
}
}
Output from the program:
Lines read from file “project/linesOnly.txt”:
[Guess who got caught?, Who?, NullPointerException., Seriously?, No. Finally.]
All lines read from file “project/linesOnly.txt”:
Guess who got caught?
Who?
NullPointerException.
Seriously?
No. Finally.
List of lines read from file “project/linesOnly.txt”:
[Guess who got caught?, Who?, NullPointerException., Seriously?, No. Finally.]
Leave a Reply