Introducing the Java NIO.2

1,464
-1

Published on

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,464
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
64
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Introducing the Java NIO.2

  1. 1. Introducing the Java NIO.2Presenters:Oscar GardunoOscar GardunoMatt KravchakMatt KravchakJoao FranciscoJoao FranciscoFadel AdoeFadel Adoe
  2. 2. Organization of Talk1. From Path to File Operations1. From Path to File Operations2. From File Operations to Managing Metadata2. From File Operations to Managing Metadata3. From Read/Write/Create to Symbolic Links3. From Read/Write/Create to Symbolic Links4. From Walking the File Tree to Legacy I/O code4. From Walking the File Tree to Legacy I/O code5. Questions or Worries?5. Questions or Worries?
  3. 3. What is a Path?● Data is stored in easily retrievable ways by afile system.– Usually in a tree structure with a root.● Paths begin at root and follow the sub-directories until the file is reached.● Microsoft Windows Ex:– C:homebillylikeToEatWarmApplePie● is used to separate directory names inWindows– / is used in the Solaris OSFrom Path to File OperationsFrom Path to File Operations
  4. 4. Ex: C:homesallystatusReportFrom Path to File OperationsFrom Path to File Operations
  5. 5. Relative of Absolute?● A path is either relative or absolute.● Absolute Paths always contain the rootelement and complete directory list necessaryto find the file.● Ex Solaris OS:– homebillylikeToEatWarmApplePie● Relative Paths need to be combined withanother path to access a file.● Ex: joe/fooFrom Path to File OperationsFrom Path to File Operations
  6. 6. Symbolic Links● Most File System objects are typically files ordirectories.● Some systems also support the notation ofsymbolic links.● Symbolic links are referred to as symlink or asoft link.● Symbolic links serve as reference to anotherfile.From Path to File OperationsFrom Path to File Operations
  7. 7. Path Class● Introduced in the Java SE 7 release.● Primary entrypoints of the java.nio.filepackage.● A Path object contains the file name anddirectory list used to construct the path, and isused to examine, locate, and manipulate files.● Note: Users with pre-JDK7 that usejava.io.File can use the Path class by usingthe File.toPath method.From Path to File OperationsFrom Path to File Operations
  8. 8. Path Class Contd● Path uses the Solaris syntax– (/home/joe/foo)● In Microsoft Windows, Path uses the Windowssyntax– (C:homejoefoo).● You cannot compare a path from Solaris topaths in Windows even if the directorystructure is identical.From Path to File OperationsFrom Path to File Operations
  9. 9. Path Class Contd● With the Path Class you can:– Create a Path– Retrieving Information About a Path– Removing Redundancies from a Path– Convert a Path– Join Two Paths– Creating a Path Between Two Paths– Comparing Two Paths● You can also use the Files class to check theexistence of the file corresponding to the PathFrom Path to File OperationsFrom Path to File Operations
  10. 10. Creating A Path● Create a Path object by using one of the following getmethods from the Paths (note the plural) helper class:– Path p1 = Paths.get("/tmp/foo")● The Paths.get method is shorthand for the followingcode:– Path p1 =FileSystems.getDefault().getPath("/tmp/foo");● The following example creates /u/joe/logs/foo.logassuming your home directory is /u/joe, orC:joelogsfoo.log if you are on Windows.– Path p5 =Paths.get(System.getProperty("user.home"),"logs", "foo.log");From Path to File OperationsFrom Path to File Operations
  11. 11. Retrieving Information about a Path● The highest element in the directory structureus located at index 0.● Lowest at index [n-1], where n is the numberof name elements in the Path.From Path to File OperationsFrom Path to File Operations
  12. 12. From Path to File OperationsFrom Path to File Operations
  13. 13. From Path to File OperationsFrom Path to File Operations
  14. 14. Removing Redundancies From Path● Many file systems use "." notation to denote the currentdirectory and ".." to denote the parent directory.– /home/./joe/foo– /home/sally/../joe/foo● The normalize method removes any redundant elements,which includes any "." or "directory/.." occurrences.● Note that normalize doesnt check at the file systemwhen it cleans up a path. It is a purely syntacticoperation.– To clean up a path while ensuring that the resultlocates the correct file, you can use thetoRealPath method.From Path to File OperationsFrom Path to File Operations
  15. 15. Converting a Path● To convert the path to a string that can beopened from a browser use toUri method– Path p1 = Paths.get("/home/logfile");– // Result is file:///home/logfile– System.out.format("%s%n", p1.toUri());● The toAbsolutePath method converts a path toan absolute path. Returns same object ifalready absolute.– // Converts the input string to a Path object.– Path inputPath = Paths.get(args[0]);– Path fullPath = inputPath.toAbsolutePath();From Path to File OperationsFrom Path to File Operations
  16. 16. Converting Path Contd● The toAbsolutePath method converts theuser input and returns a Path that returnsuseful values when queried.● File does not have to exist in order fortoAbsoluteMethod to work.From Path to File OperationsFrom Path to File Operations
  17. 17. Converting a Path Contd● The toRealPath method returns the real pathof an existing file. Operations:– If true is passed to this method and the filesystem supports symbolic links, this methodresolves any symbolic links in the path.– If the Path is relative, it returns an absolutepath.– If the Path contains any redundant elements, itreturns a path with those elements removed.From Path to File OperationsFrom Path to File Operations
  18. 18. Joining Two Paths● Resolve method combines paths● You pass in a partial path , which is a paththat does not include a root element, and thatpartial path is appended to the original path.● Ex:– // Microsoft Windows– Path p1 = Paths.get("C:homejoefoo");– // Result is C:homejoefoobar– System.out.format("%s%n", p1.resolve("bar"));From Path to File OperationsFrom Path to File Operations
  19. 19. ● Passing an absolute path to the resolvemethod returns the passed-in path:– // Solaris– Path p1 = Paths.get("/home/joe/foo");– // Result is /home/joe– Paths.get("foo").resolve("/home/joe");From Path to File OperationsFrom Path to File Operations
  20. 20. Creating a Path Between Two Paths● Relativize method constructs a path from onelocation in the file system to another location.– The new path is relative to the original path.● Ex given joe and sally are nodes that reside atthe same level in the tree structure:– Path p1 = Paths.get("joe");– Path p2 = Paths.get("sally");– // Result is ../sally– Path p1_to_p2 = p1.relativize(p2);– // Result is ../joe– Path p2_to_p1 = p2.relativize(p1);From Path to File OperationsFrom Path to File Operations
  21. 21. Comparing Two Paths● The Path class supports equals, enabling youto test two paths for equality.● The startsWith and endsWith methods enableyou to test whether a path begins or ends witha particular string.● Ex:–From Path to File OperationsFrom Path to File Operations
  22. 22. Useful Methods● Iterator returns an object that enables you toiterate over the name elements in the path.● Ex iteration over a path, printing each nameelement:– Path path = ...;– for (Path name: path) {– System.out.println(name); }● Path also implements the Comparableinterface by using compareTo – useful forsorting.From Path to File OperationsFrom Path to File Operations
  23. 23. File Operations● The file class is the other primary entrypoint ofthe java.nio.file package.● This class offers a rich set of static methodsfor reading, writing, and manipulating files anddirectories.● The Files methods work on instances of Pathobjects.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  24. 24. Checking a File or Directory● You have a Path instance representing a file ordirectory, but does that file exist on the file system?Is it readable? Writable? Executable?● You can do so with exists(Path, LinkOption...) andthe notExists(Path, LinkOption...) methods.● When you are testing a files existence, three resultsare possible:● The file is verified to exist.● The file is verified to not exist.● The files status is unknown. This result can occurwhen the program does not have access to the file.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  25. 25. Checking File Accessibility● To verify that the program can access a file asneeded, you can use the isReadable(Path),isWritable(Path), and isExecutable(Path) methods.● Code:Path file = ...;boolean isRegularExecutableFile = Files.isRegularFile(file) &Files.isReadable(file) & Files.isExecutable(file);From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  26. 26. Checking Whether Two Paths Locate theSame File● When you have a file system that uses symboliclinks, it is possible to have two different paths thatlocate the same file.● The isSameFile(Path, Path) method compares twopaths to determine if they locate the same file on thefile system.● Code:Path p1 = ...;Path p2 = ...;if (Files.isSameFile(p1, p2)) {// Logic when the paths locate the same file}From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  27. 27. Deleting a File or Directory● You can delete files, directories or links● With symbolic links, the link is deleted and not the targetof the link. With directories, the directory must be empty,or the deletion fails.● The Files class provides two deletion methods.● The delete(Path) method deletes the file or throws anexception if the deletion fails.● The deleteIfExists(Path) method also deletes the file, butif the file does not exist, no exception is thrown.● Failing silently is useful when you have multiple threadsdeleting files and you dont want to throw an exceptionjust because one thread did so first.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  28. 28. Deleting a File or Directory● Code:try {Files.delete(path);} catch (NoSuchFileException x) {System.err.format("%s: no such" + " file or directory%n",path);} catch (DirectoryNotEmptyException x) {System.err.format("%s not empty%n", path);} catch (IOException x) {// File permission problems are caught here.System.err.println(x);}From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  29. 29. Deleting a File or Directory● The deleteIfExists(Path) method also deletesthe file, but if the file does not exist, noexception is thrown.● Failing silently is useful when you havemultiple threads deleting files and you dontwant to throw an exception just because onethread did so first.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  30. 30. Copying a File or Directory● You can copy a file or directory by using the copy(Path,Path, CopyOption...) method.● The copy fails if the target file exists, unless theREPLACE_EXISTING option is specified.● Directories can be copied. However, files inside thedirectory are not copied, so the new directory is emptyeven when the original directory contains files.● When copying a symbolic link, the target of the link iscopied.● If you want to copy the link itself, and not the contents ofthe link, specify either the NOFOLLOW_LINKS orREPLACE_EXISTING option.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  31. 31. Moving a File or Directory● You can move a file or directory by using the move(Path,Path, CopyOption...) method.● The move fails if the target file exists, unless theREPLACE_EXISTING option is specified.● Empty directories can be moved. If the directory is notempty, the move is allowed when the directory can bemoved without moving the contents of that directory.● On UNIX systems, moving a directory within the samepartition generally consists of renaming the directory.● In that situation, this method works even when thedirectory contains files.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  32. 32. Managing Metadata● The definition of metadata is "data about otherdata."● With a file system, the data is contained in itsfiles and directories, and the metadata tracksinformation about each of these objects.● Is it a regular file, a directory, or a link? Whatis its size, creation date, last modified date, fileowner, group owner, and access permissions?From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  33. 33. Managing Metadata● A file systems metadata is typically referred toas its file attributes.● The Files class includes methods that can beused to obtain a single attribute of a file, or toset an attribute.● http://docs.oracle.com/javase/tutorial/essential/io/fFrom File Operations to Managing MetadataFrom File Operations to Managing Metadata
  34. 34. Managing Metadata● If a program needs multiple file attributes around the sametime, it can be inefficient to use methods that retrieve a singleattribute.● Repeatedly accessing the file system to retrieve a singleattribute can adversely affect performance.● For this reason, the Files class provides two readAttributesmethods to fetch a files attributes in one bulk operation.● readAttributes(Path, String, LinkOption...) Reads a filesattributes as a bulk operation. The String parameter identifiesthe attributes to be read.● readAttributes(Path, Class<A>, LinkOption...) Reads a filesattributes as a bulk operation. The Class<A> parameter is thetype of attributes requested and the method returns an objectof that class.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  35. 35. Managing Metadata● Different file systems have different notionsabout which attributes should be tracked.● For this reason, related file attributes aregrouped together into views.● A view maps to a particular file systemimplementation, such as POSIX or DOS, or toa common functionality, such as fileownership.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  36. 36. Managing Metadata● BasicFileAttributeView – Provides a view of basic attributes that are required to besupported by all file system implementations.● DosFileAttributeView – Extends the basic attribute view with the standard four bitssupported on file systems that support the DOS attributes.● PosixFileAttributeView – Extends the basic attribute view with attributes supportedon file systems that support the POSIX family of standards, such as UNIX. Theseattributes include file owner, group owner, and the nine related access permissions.● FileOwnerAttributeView – Supported by any file system implementation thatsupports the concept of a file owner.● AclFileAttributeView – Supports reading or updating a files Access Control Lists(ACL). The NFSv4 ACL model is supported. Any ACL model, such as the WindowsACL model, that has a well-defined mapping to the NFSv4 model might also besupported.● UserDefinedFileAttributeView – Enables support of metadata that is user defined.This view can be mapped to any extension mechanisms that a system supports. Inthe Solaris OS, for example, you can use this view to store the MIME type of a file.From File Operations to Managing MetadataFrom File Operations to Managing Metadata
  37. 37. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
  38. 38. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Small Files● READING ALL BYTES OR LINES FROM A FILE:Use readAllBytes(Path) or readAllLines(Path, Charset)Path file = ...;byte[] fileArray;fileArray =Files.readAllBytes(file);● WRITING ALL BYTES OR LINES FROM A FILE:Use write(Path, byte[], OpenOption...) or write(Path, Iterable<extends CharSequence>, Charset, OpenOption...)Path file = ...;byte[] fileArray;fileArray =Files.readAllBytes(file);
  39. 39. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Text Files (Buffered Streams)● ADVANTAGES: supports channel I/O, which moves data in buffer(can be faster overall)● READING A FILE:Use readAllBytes(Path) or readAllLines(Path, Charset)Charset charset = Charset.forName("US-ASCII");try (BufferedReader reader = Files.newBufferedReader(file,charset)) {String line = null;while ((line = reader.readLine()) != null) {System.out.println(line);}} catch (IOException x) {System.err.format("IOException: %s%n", x);}
  40. 40. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Text Files (Buffered Streams)● ADVANTAGES: supports channel I/O, which moves data in buffer(can be faster overall)● WRITING A FILE:Use newBufferedWriter(Path, Charset, OpenOption...)Charset charset = Charset.forName("US-ASCII");String s = ...;try (BufferedWriter writer = Files.newBufferedWriter(file, charset)){writer.write(s, 0, s.length());} catch (IOException x) {System.err.format("IOException: %s%n", x);}
  41. 41. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Unbuffered Streams● READING A FILE:Use newInputStream(Path, OpenOption...)Path file = ...;try (InputStream in = Files.newInputStream(file);BufferedReader reader =new BufferedReader(new InputStreamReader(in))) {String line = null;while ((line = reader.readLine()) != null) {System.out.println(line);}} catch (IOException x) {System.err.println(x);}
  42. 42. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Unbuffered Streams● WRITING A FILE:Use newOutputStream(Path, OpenOption...)Path logfile = ...;// Convert the string to a// byte array.String s = ...;byte data[] = s.getBytes();try (OutputStream out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND))) {...out.write(data, 0, data.length);} catch (IOException x) {System.err.println(x);}
  43. 43. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Channels and ByteBuffers● ADVANTAGES: can read more than 1 character at a time (reads a buffer at a time)● READING AND WRITING A FILE:Use newByteChannel(Path, OpenOption...) or newByteChannel(Path, Set<?extends OpenOption>, FileAttribute<?>...)// Reading a Filetry (SeekableByteChannel sbc = Files.newByteChannel(file)) {ByteBuffer buf = ByteBuffer.allocate(10);// Read the bytes with the proper encoding for this platform. If// you skip this step, you might see something that looks like// Chinese characters when you expect Latin-style characters.String encoding = System.getProperty("file.encoding");while (sbc.read(buf) > 0) {buf.rewind();System.out.print(Charset.forName(encoding).decode(buf));buf.flip();}} catch (IOException x) {System.out.println("caught exception: " + x);
  44. 44. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCommon Methods for Channels and ByteBuffers// Create a LOG fileimport static java.nio.file.StandardCopyOption.*;// Create the set of options for appending to the file.Set<OpenOptions> options = new HashSet<OpenOption>();options.add(APPEND);options.add(CREATE);// Create the custom permissions attribute.Set<PosixFilePermission> perms =PosixFilePermissions.fromString("rw-r------");FileAttribute<Set<PosixFilePermission>> attr =PosixFilePermissions.asFileAttribute(perms);// Convert the string to a ByteBuffer.String s = ...;byte data[] = s.getBytes();ByteBuffer bb = ByteBuffer.wrap(data);try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) {sbc.write(bb);} catch (IOException x) {System.out.println("exception thrown: " + x);}
  45. 45. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCreating Files● CREATING AN EMPTY FILE: (Atomic Operation)Use createFile(Path, FileAttribute<?>)Path file = ...;try {// Create the empty file with default permissions, etc.Files.createFile(file);} catch (FileAlreadyExistsException x) {System.err.format("file named %s" +" already exists%n", file);} catch (IOException x) {// Some other sort of failure, such as permissions.System.err.format("createFile error: %s%n", x);}
  46. 46. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksCreating Files● CREATING A TEMPORARY FILE: (Atomic Operation)Use createTempFile(Path, String, String, FileAttribute<?>) orcreateTempFile(String, String, FileAttribute<?>)try {Path tempFile = Files.createTempFile(null, ".myapp");System.out.format("The temporary file" +" has been created: %s%n", tempFile);} catch (IOException x) {System.err.format("IOException: %s%n", x);}The result would be something like:The temporary file has been created:/tmp/509668702974537184.myapp
  47. 47. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksRandom Access Files● READING AND WRITING:Use the SeekableByteChannel interfaceString s = "I was here!n";byte data[] = s.getBytes();ByteBuffer out = ByteBuffer.wrap(data);ByteBuffer copy = ByteBuffer.allocate(12);try (FileChannel fc = (FileChannel.open(file,READ, WRITE))) {// Read the first 12// bytes of the file.int nread;do {nread = fc.read(copy);} while (nread != -1 &&copy.hasRemaining());// Write "I was here!" at the beginning of thefile.fc.position(0);while (out.hasRemaining())fc.write(out);out.rewind();// Move to the end of the file. Copy the first12 bytes to// the end of the file. Then write "I washere!" again.long length = fc.size();fc.position(length-1);copy.flip();while (copy.hasRemaining())fc.write(copy);while (out.hasRemaining())fc.write(out);} catch (IOException x) {System.out.println("I/O Exception: " + x);}
  48. 48. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksManipulating Directories● CREATING A DIRECTORY:Use createDirectory(Path, FileAttribute<?>)Path dir = ...;Files.createDirectory(path);● LISTING A DIRECTORYS CONTENTS:Use newDirectoryStream(Path)Path dir = ...;try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {for (Path file: stream) {System.out.println(file.getFileName());}} catch (IOException | DirectoryIteratorException x) {// IOException can never be thrown by the iteration.// In this snippet, it can only be thrown by newDirectoryStream.System.err.println(x);}
  49. 49. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksSymbolic Links● The java.nio.file package, and the Path class in particular, is "link aware." EveryPath method either detects what to do when a symbolic link is encountered, or itprovides an option enabling you to configure the behavior when a symbolic link isencountered.● CREATING A SYMBOLIC LINK:Use createSymbolicLink(Path, Path, FileAttribute<?>)Path newLink = ...;Path target = ...;try {Files.createSymbolicLink(newLink, target);} catch (IOException x) {System.err.println(x);} catch (UnsupportedOperationException x) {// Some file systems do not support symbolic links.System.err.println(x);}
  50. 50. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksSymbolic Links● CREATING A HARD LINK:Use createLink(Path, Path)Path newLink = ...;Path existingFile = ...;try {Files.createLink(newLink, existingFile);} catch (IOException x) {System.err.println(x);} catch (UnsupportedOperationException x) {// Some file systems do not// support adding an existing// file to a directory.System.err.println(x);}
  51. 51. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic LinksksSymbolic Links● DETECTING A SYMBOLIC LINK:Use isSymbolicLink(Path)Path file = ...;boolean isSymbolicLink=Files.isSymbolicLink(file);● FINDING THE TARGET OF A SYMBOLIC LINK:Use readSymbolicLink(Path)Path link = ...;try {System.out.format("Target of link" +" %s is %s%n", link,Files.readSymbolicLink(link));} catch (IOException x) {System.err.println(x);}// If the path is not a link, it throws a NotLinkException
  52. 52. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeThe FileVisitor Interface1. preVisitDirectory2. postVisitDirectory3. visitFile4. visitFileFailed
  53. 53. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeThe FileVisitor Interface implementedimport static java.nio.file.FileVisitResult.*;public static class PrintFilesextends SimpleFileVisitor<Path> {// Print information about// each type of file.@Overridepublic FileVisitResult visitFile(Path file,BasicFileAttributes attr) {if (attr.isSymbolicLink()) {System.out.format("Symbolic link: %s ", file);} else if (attr.isRegularFile()) {System.out.format("Regular file: %s ", file);} else {System.out.format("Other: %s ", file);}System.out.println("(" + attr.size() + "bytes)");return CONTINUE;}// Print each directory visited.@Overridepublic FileVisitResult postVisitDirectory(Path dir,IOException exc) {System.out.format("Directory: %s%n", dir);return CONTINUE;}// If there is some error accessing// the file, let the user know.// If you dont override this method// and an error occurs, an IOException// is thrown.@Overridepublic FileVisitResult visitFileFailed(Path file,IOException exc) {System.err.println(exc);return CONTINUE;}}
  54. 54. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeKickstarting the ProcessPath startingDir = ...;PrintFiles pf = new PrintFiles();Files.walkFileTree(startingDir, pf);Technical Note:The tree traversal is depth first search, but subdirectories traversal is non-deterministicControlling the Tree Traversalimport static java.nio.file.FileVisitResult.*;// The file we are looking for.Path lookingFor = ...;public FileVisitResultvisitFile(Path file,BasicFileAttributes attr) {if (file.getFileName().equals(lookingFor)) {System.out.println("Located file: " + file);return TERMINATE;}return CONTINUE;}import static java.nio.file.FileVisitResult.*;public FileVisitResultpreVisitDirectory(Path dir,BasicFileAttributes attrs) {(if (dir.getFileName().toString().equals("SCCS")) {return SKIP_SUBTREE;}return CONTINUE;}
  55. 55. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeFinding FilesPathMatcher matcher =FileSystems.getDefault().getPathMatcher("glob:*.{java,class}");Path filename = ...;if (matcher.matches(filename)) {System.out.println(filename);}Watching a Directory for Changes: The Watch Service API1. Create a WatchService "watcher" for the file system.2. Register Directories with the watcherr.3. Implement an infinite loop to wait for incoming events. When an event occurs, the key is signaled and placed into the watchersqueue.4. Retrieve the key from the watchers queue. You can obtain the file name from the key.5. Retrieve each pending event for the key (there might be multiple events) and process as needed.6Reset the key, and resume waiting for events.7 Close the service: The watch service exits when either the thread exits or when it is closed (by invoking its closed method).
  56. 56. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeWatching a Directory for Changes: The Watch Service APIimport static java.nio.file.StandardWatchEventKinds.*;Path dir = ...;try {WatchKey key = dir.register(watcher,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);} catch (IOException x) {System.err.println(x);}for (;;) {// wait for key to be signaledWatchKey key;try {key = watcher.take();} catch (InterruptedException x) {return;}for (WatchEvent<?> event: key.pollEvents()) {WatchEvent.Kind<?> kind = event.kind();if (kind == OVERFLOW) {continue;}// The filename is the// context of the event.WatchEvent<Path> ev = (WatchEvent<Path>)event;Path filename = ev.context();try {Path child = dir.resolve(filename);if (!Files.probeContentType(child).equals("text/plain")) {System.err.format("New file %s" +" is not a plain text file.%n", filename);continue;}} catch (IOException x) {System.err.println(x);continue;}System.out.format("Emailing file %s%n", filename);//Details left to reader....}boolean valid = key.reset();if (!valid) {break;}
  57. 57. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O codeInteroperability with Legacy CodeSmile :), it is just a single line of code to convert fromjava.io.File to java.nio.filePath nioPath = oldFile.toPath();Now, continue with your java.nio.path cruise :)
  58. 58. What We Told you earlier and wish to tell youWhat We Told you earlier and wish to tell youAgain!Again!The Path class: use it to manipulate pathsThe File class: use it for file operations, such as moving,coping, deleting, and ...The FileSystem class: use it to obtain infomation about the filesystem
  59. 59. ReferencesReferenceshttp://docs.oracle.com/javase/tutorial/essential/io/fileio.html

×