Java 7 - short intro to NIO.2

  • 3,557 views
Uploaded 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!

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!

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,557
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
79
Comments
0
Likes
7

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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