mercoledì 12 febbraio 2014

NIO 2

If like many Java developers you struggle each time you have to read or write a file, Java SE 7 came to your rescue by introducing a new IO package: java.nio. With a more expressive syntax, its goal is to replace the existing java.io package to allow:

  • A cleaner exception handling.
  • Full access to the file system with new features (support of specific operating system attributes,  •
  • symbolic links, etc.).
  • The addition of the notion of  FileSystemand FileStore(e.g., a partition disk).
  • Utility methods (move/copy files, read/write binary or text files, path, directories, etc.). 

The following code shows you the new java.nio.file.Pathinterface (used to locate a file or a directory in a file system) as well as the utility class java.nio.file.Files(used to get information about the file or to manipulate it). From Java SE 7 onward it is recommended to use the new NIO.2 even if the old java.io package has not been deprecated.
The following code, gets some information about the source.txt file, copies it to the dest.txt file, displays its content, and deletes it.
Path path = Paths.get("source.txt");

boolean exists = Files.exists(path);

boolean isDirectory = Files.isDirectory(path);

boolean isExecutable = Files.isExecutable(path);

boolean isHidden = Files.isHidden(path);

boolean isReadable = Files.isReadable(path);

boolean isRegularFile = Files.isRegularFile(path);

boolean isWritable = Files.isWritable(path);

long size = Files.size(path);

// Copies a file

Files.copy(Paths.get("source.txt"), Paths.get("dest.txt"));

// Reads a text file

List<String> lines = Files.readAllLines(Paths.get("source.txt"), UTF_8);

for (String line : lines) {

  System.out.println(line);

}

// Deletes a file

Files.delete(path);

Nessun commento:

Posta un commento