Java 7 - short intro to NIO.2


Published on

NIO.2 slides out of the Back to the Future with Java 7 presentation. For free use by NIO.2 developers to help them spread the word!

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java 7 - short intro to NIO.2

  1. 1. Back to the Future with Java 7 <ul><li>Martijn Verburg </li></ul><ul><li>( @karianna , @java7developer ) </li></ul><ul><li> </li></ul>Slide Design by
  2. 2. NIO.2 - New I/O version 2 <ul><li>Is aimed at simplifying I/O in Java </li></ul><ul><li>A new file system and path abstraction </li></ul><ul><ul><li>Based on java.nio.file.Path </li></ul></ul><ul><ul><li>Bulk access to file attributes </li></ul></ul><ul><ul><li>File system specific support (e.g. Symbolic links) </li></ul></ul><ul><ul><li>Extra providers (e.g. zip files treated as normal files) </li></ul></ul><ul><li>Asynchronous (non-blocking) I/O </li></ul><ul><ul><li>For sockets and files </li></ul></ul><ul><ul><li>Mainly utilises java.util.concurrent.Future </li></ul></ul><ul><li>Socket/Channel construct </li></ul><ul><ul><li>Binding, options and multicast </li></ul></ul>13 13
  3. 3. NIO.2 - Path <ul><li>java.nio2.file.Path interface </li></ul><ul><ul><li>Typically represents a file on a file system </li></ul></ul><ul><ul><li>normalize() method removes constructs such as . and .. in a Path </li></ul></ul><ul><ul><li>relativize(Path) constructs relative Path between this path and the one given </li></ul></ul><ul><ul><li>Lots of other expected methods defined in the interface </li></ul></ul><ul><ul><ul><li>Dealing with real path, absolute path etc </li></ul></ul></ul><ul><ul><li>Can convert objects </li></ul></ul><ul><ul><ul><li>Via the public Path toPath() method </li></ul></ul></ul><ul><li>java.nio2.file.Paths </li></ul><ul><ul><li>Helper class, provides get(URI) method to return you a Path </li></ul></ul><ul><ul><ul><li>Uses FileSystems helper class under the hood </li></ul></ul></ul><ul><ul><ul><li>Uses the default file system unless you specify otherwise </li></ul></ul></ul>
  4. 4. NIO.2 - Path - Some quick exploration <ul><li>// Get foobar.txt </li></ul><ul><li>Path path = Paths.get( &quot;../foobar.txt&quot; ); </li></ul><ul><li>// Normalise the path (get rid of the ..) </li></ul><ul><li>Path normalizedPath = path.normalize(); </li></ul><ul><li>// Get the parent Path of the file </li></ul><ul><li>Path parent = path.getParent(); </li></ul><ul><li>// Get the absolute Path of the file </li></ul><ul><li>boolean isAbsolute = path.isAbsolute(); </li></ul><ul><li>    </li></ul><ul><li>// Figure out the relative Path between two files </li></ul><ul><li>Path barFile = Paths.get( &quot;../../bar.txt&quot; ) </li></ul><ul><li>Path pathBetweenFiles = path.relativize(barFile); </li></ul><ul><li>// Interoperate with </li></ul><ul><li> file = path.toFile(); </li></ul>
  5. 5. NIO.2 - Files <ul><li>java.nio2.file.Files helper class </li></ul><ul><ul><li>Day to day class for performing simple file I/O </li></ul></ul><ul><li>Many common methods </li></ul><ul><ul><li>copy </li></ul></ul><ul><ul><li>delete </li></ul></ul><ul><ul><li>move </li></ul></ul><ul><ul><li>createDirectory/File/Link </li></ul></ul><ul><ul><li>write </li></ul></ul><ul><ul><li>readAllLines </li></ul></ul><ul><ul><li>walkFileTree (recurse over a directory) </li></ul></ul><ul><ul><li>newInputStream/OutputStream </li></ul></ul><ul><li>Combined with try -with-resources makes code concise </li></ul>
  6. 6. NIO.2 - Files - Some quick exploration <ul><li>Path timeSheetFile = Paths.get( &quot;C:/projects/timesheet.txt&quot; ); </li></ul><ul><li>Path backupDir = Paths.get( &quot;H:/projects/&quot; ); </li></ul><ul><li>// Create the backup directory </li></ul><ul><li>Files.createDirectory(backupDir); </li></ul><ul><li>// Check that the file actually exists </li></ul><ul><li>// Don’t follow any symbolic links </li></ul><ul><li>boolean fileExists = Files.exists(timeSheetFile, </li></ul><ul><li>LinkOption.NOFOLLOW_LINKS); </li></ul><ul><li>  </li></ul><ul><li>// Simple copy with overwrite </li></ul><ul><li>CopyOption copyOptions = StandardCopyOption.REPLACE_EXISTING; </li></ul><ul><li>Files.copy(timeSheetFile, timeSheetFileBackup, copyOptions); </li></ul><ul><li>// Read all of the lines </li></ul><ul><li>List<String> lines = Files.readAllLines(timeSheetFile, </li></ul><ul><li>Charset.defaultCharset()); </li></ul>
  7. 7. NIO.2 - Files - Some quick exploration II <ul><ul><li>// Move a file, copying over its attributes as well </li></ul></ul><ul><li>Files.move(timeSheetFile, backupDir, </li></ul><ul><li>              StandardCopyOption.REPLACE_EXISTING, </li></ul><ul><li>              StandardCopyOption.COPY_ATTRIBUTES);      </li></ul><ul><li>// Delete a file </li></ul><ul><li>Files.deleteIfExists(timeSheetFile); </li></ul>
  8. 8. URLStream to file - Java 6 <ul><li>URL url = </li></ul><ul><li>new URL( &quot; &quot; ); </li></ul><ul><li>try ( </li></ul><ul><li>FileOutputStream fos = </li></ul><ul><li>new FileOutputStream( new File( &quot;output.txt&quot; )); </li></ul><ul><li>InputStream is = url.openStream() ) </li></ul><ul><li>{ </li></ul><ul><li>byte [] buf = new byte [4096]; </li></ul><ul><li>int len; </li></ul><ul><li>while ((len = > 0) </li></ul><ul><li>{ </li></ul><ul><li>fos.write(buf, 0, len); </li></ul><ul><li>} </li></ul><ul><li>} catch (IOException e) </li></ul><ul><li>{ </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} </li></ul>
  9. 9. URL stream to file in Java 7 <ul><li>// Ignoring the MalformedURLException </li></ul><ul><li>URL url = </li></ul><ul><li>new URL( &quot; &quot; ); </li></ul><ul><li>try (InputStream in = url.openStream()) </li></ul><ul><li>{ </li></ul><ul><li>Files.copy(in, Paths.get( &quot;output.txt&quot; )); </li></ul><ul><li>} </li></ul><ul><li>catch (IOException ex) </li></ul><ul><li>{ </li></ul><ul><li>ex.printStackTrace(); </li></ul><ul><li>} </li></ul>
  10. 10. NIO.2 - Asynchronous I/O <ul><li>The ability to perform read/write operations in the background </li></ul><ul><ul><li>Without having to write your own java.util.concurrent code </li></ul></ul><ul><li>Is available for: </li></ul><ul><ul><li>file I/O ( AsynchronousFileChannel ) </li></ul></ul><ul><ul><li>networking I/O ( AsynchronousSocketChannel ) </li></ul></ul><ul><ul><ul><li>And AsynchronousServerSocketChannel </li></ul></ul></ul><ul><li>Can work in two styles </li></ul><ul><ul><li>Future based (order coffee, do something else, collect coffee) </li></ul></ul><ul><ul><li>Callbacks (order coffee, do something else, have coffee thrown at you) </li></ul></ul>
  11. 11. NIO.2 - Future based file I/O example <ul><li>try { </li></ul><ul><li>Path file = Paths.get( &quot;/usr/karianna/foobar.txt&quot; ); </li></ul><ul><li>AsynchronousFileChannel channel = </li></ul><ul><li>; </li></ul><ul><li>ByteBuffer buffer = ByteBuffer.allocate(100_000_000_000); </li></ul><ul><li>Future<Integer> result =, 0); </li></ul><ul><li>while (!result.isDone()) { </li></ul><ul><li>System.out.println( &quot;Do some other stuff&quot; ); </li></ul><ul><li>} </li></ul><ul><li>Integer bytesRead = result.get(); </li></ul><ul><li>} catch (IOException | ExecutionException | InterruptedException e) </li></ul><ul><li>{ </li></ul><ul><li>// Deal with exception </li></ul><ul><li>} </li></ul>
  12. 12. NIO.2 - Callback based file I/O example <ul><li>try { </li></ul><ul><li>Path file = Paths.get(&quot;/usr/karianna/foobar.txt&quot;); </li></ul><ul><li>AsynchronousFileChannel channel =; </li></ul><ul><li>ByteBuffer buffer = ByteBuffer.allocate(100_000_000_000); </li></ul><ul><li>, 0, buffer, </li></ul><ul><li>new CompletionHandler<Integer, ByteBuffer>() { </li></ul><ul><li>    public void completed(Integer result, ByteBuffer attachment) { </li></ul><ul><li>        System.out.println( &quot;Bytes read [&quot; + result + &quot;]&quot; ); </li></ul><ul><li>        } </li></ul><ul><li>        public void failed(Throwable exception, ByteBuffer attachment) { </li></ul><ul><li>        // Deal with exception </li></ul><ul><li>        } </li></ul><ul><li>    }); </li></ul><ul><li>} catch (IOException e) { </li></ul><ul><li>    // Deal with exception </li></ul><ul><li>} </li></ul>
  13. 13. Thanks for listening! ( ) )