Reading and Writing Bytes
The Files class also provides methods for reading and writing bytes to files. These methods that can be categorized as follows:
- Methods that create low-level byte I/O streams (InputStream, OutputStream) chained to a Path object that denotes a file. The methods of the I/O streams can then be used to read and write bytes to the file.
- Methods that directly use a Path object, and read and write bytes to the file denoted by the Path object.
Reading and Writing Bytes Using I/O Streams
The newInputStream() and newOutputStream() methods of the Files class create an input stream and an output stream, respectively, that are chained to a Path object denoting a file. Interoperability between I/O streams in the java.io package can then be leveraged to chain appropriate I/O streams for reading and writing data to a file (ยง20.2, p. 1234).
static InputStream newInputStream(Path path, OpenOption… options)
throws IOException
Opens a file denoted by the specified path, and returns an input stream to read from the file. No options implies the READ option.
static OutputStream newOutputStream(Path path, OpenOption… options)
throws IOException
Opens or creates a file denoted by the specified path, and returns an output stream that can be used to write bytes to the file. No options implies the following options: CREATE, TRUNCATE_EXISTING, and WRITE.
Previously we have seen how the copy() methods of the Files class use byte I/O streams for reading and writing bytes to files (p. 1311).
The code at (1) in Example 21.3 is a reworking of Example 20.1, p. 1237, to copy bytes from a source file to a destination file using an explicit byte buffer. The main difference is that the input stream and the output stream on the respective files are created by the newInputStream() and newOutputStream() methods of the Files class, based on Path objects that denote the files, rather than on file I/O streams. As before, the methods read() and write() of the InputStream and OutputStream classes, respectively, are used to read and write the bytes from the source file to the destination file using a byte buffer.
Example 21.3 Reading and Writing Bytes
import java.io.*;
import java.nio.file.*;
public class ReadingWritingBytes {
public static void main(String[] args) {
// Source and destination files:
Path srcPath = Path.of(“project”, “source.dat”);
Path destPath = Path.of(“project”, “destination.dat”);
try (InputStream is = Files.newInputStream(srcPath); // (1)
OutputStream os = Files.newOutputStream(destPath)) {
byte[] buffer = new byte[1024];
int length = 0;
while((length = is.read(buffer, 0, buffer.length)) != -1) {
os.write(buffer, 0, length);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
// Reads the file contents into an array of bytes:
byte[] allBytes = Files.readAllBytes(srcPath); // (2)
// Writes an array of bytes to a file:
Files.write(destPath, allBytes); // (3)
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Leave a Reply