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.
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.
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.
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:
Leave a Reply