Reading and Writing Bytes Using Path Objects – Java I/O: Part II

Reading and Writing Bytes Using Path Objects

The Files class provides methods that directly use a Path object, and read and write bytes to the file denoted by the Path object, without the need to specify a file I/O stream. The method readAllBytes() reads all bytes from a file into a byte array in one operation, and the method write() writes the bytes in a byte array to a file. These methods also close the file when done.

Click here to view code image

static byte[] readAllBytes(Path path) throws IOException

Reads all the bytes from the file denoted by the specified path. The bytes are returned in a byte array.

Click here to view code image

static Path write(Path path, byte[] bytes, OpenOption… options)
            throws IOException

Writes bytes in a byte array to the file denoted by the specified path. No options implies the following options: CREATE, TRUNCATE_EXISTING, and WRITE.

The code at (2) and (3) in Example 21.3 shows yet another example of copying the contents of a source file to a destination file. The readAllBytes() and write() methods accomplish the task in a single call to each method.

Click here to view code image

byte[] allBytes = Files.readAllBytes(srcPath);                        // (2)

Files.write(destPath, allBytes);                                      // (3)

Note that these methods are meant for simple cases, and not for handling large files, as data is handled using an array of bytes.

21.6 Managing File Attributes

Useful metadata is associated with directory entries in a file system—for example, the file permissions that indicate whether the entry is readable or writable, or whether it is a symbolic link, and its size. Such metadata in the file system is often referred to as file attributes. Managing file attributes is a separate concern from the data that is stored in files.

There are basically two approaches provided by the NIO.2 API for managing file attributes:

  • Accessing individual file attributes associated with a directory entry in the file system (p. 1321)
  • Accessing a set of file attributes associated with a directory entry in the file system as a bulk operation (p. 1328)
Categories: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *