An overview of software development methodologies.
NIO.2, the I/O API for the future
1. NIO.2: The I/O API For Future Masoud Kalali [email_address] Twitter: @MasoudKalali http://kalali.me
2.
3. Java I/O history from Java 1.0 to Java 7 I/O in Java 1.1 NIO (JSR-51) in JDK 1.4 NIO.2 (JSR-203) in Java 7
4.
5.
6.
7. How the NIO.2 works FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath("/home/masoud/simple.txt"); try { p.deleteIfExists(); } catch (IOException ex) { //handle it } Basically everything start with FileSystems and FileSystem object
8.
9.
10. Walking The File System Tree • Files.walkFileTree * Walks a file tree from a given starting path down to the given depth * Invoke FileVisitor methods for each file/directory public class SimpleVisitor { public static void main(String args[]) { FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath("/home/masoud/"); MyVisit v = new MyVisit(); Files.walkFileTree(p, EnumSet.allOf(FileVisitOption.class), 2, v); } } class MyVisit extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { System.out.println(file.getName()); return super.visitFile(file, attrs); } } PreVisitDirectory PreVisitDirectoryFailed VisitFile VisitFileFailed postVisitDirectory
11.
12. File attributes and metadata: basic attributes BasicFileAttributes: Common to all FS and contains basic attributes. Creation Time Last Access Time Modification Time Size File Type: isDirectory, IsFile, IsSymbolicLink, IsOther File Key FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath("/home/masoud/simple"); BasicFileAttributeView bav= p.getFileAttributeView(BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); BasicFileAttributes ba =bav.readAttributes(); System.out.println(p.toString() + " last access: " + ba.lastAccessTime()); System.out.println(p.toString() + " last modified: " + ba.lastModifiedTime());
13. File attributes and metadata: Platform specific Attributes PosixFileAttributeView Extends BasicFileAttributeView, contain Posix specific attributes. FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath("/home/masoud/photo.png"); Set<String> supportedViews = fs.supportedFileAttributeViews(); if (supportedViews.contains("unix")) { PosixFileAttributes pat = Attributes.readPosixFileAttributes(p, LinkOption.NOFOLLOW_LINKS); System.out.println(pat.group().getName()); System.out.println(pat.owner(). } All Basic attributes Retrieving group Retrieving owner Retrieving permission basic unix dos acl owner user etc.
14.
15.
16. //Setting permissions Set<PosixFilePermission> st = PosixFilePermissions.fromString("rwxrwxrwx"); Attributes.setPosixFilePermissions(p, st2); //Setting the owner username, we should find the user prior to using Attributes utility class UserPrincipal up = s.getUserPrincipalLookupService().lookupPrincipalByName("masoud"); Attributes.setOwner(p, up); //Another way to set the owner name. FileOwnerAttributeView fo = p.getFileAttributeView(FileOwnerAttributeView.class, LinkOption.NOFOLLOW_LINKS); fo.setOwner(up); FileOwnerView: Deal with file owner attribute Attributes: To write attributes, PosixFileAttributes includes permissions as well. File attributes and metadata: Managing POSIX files permissions
17. FileStore features The FileStore : Represent the file system underlying storage devices, pools, partitions, and so on. FileSystem fs = FileSystems.getFileSystem(new URI("File:///")); Path p = fs.getPath("/home/masoud"); FileStore fstore = p.getFileStore(); FileStoreSpaceAttributes attrs = Attributes.readFileStoreSpaceAttributes(fstore); long total = attrs.totalSpace() / (1024*1024); long used = (attrs.totalSpace() - attrs.unallocatedSpace()) / (1024*1024); long avail = attrs.usableSpace() /(1024*1024); System.out.println(" device size(MB) used(MB) available(MB) "); System.out.format("%-20s %12d %12d %12d%n", fstore, total, used, avail); We can use FileSystem.getFileStores() to get all underlying file stores.
22. Blocking, Non-Blocking and Asynchronous I/O Prior to Java SE 1.4 : Everything was blocking and and use of threads was inevitable. ( which causes scalability issues and performance overhead) Java SE 1.4 : Brings the JSR-51 or NIO with non-blocking IO; Introduction of channels and selectors. Non-Blocking not Asynchronous. Java SE 7 : Addition of asynchronous IO to the pack; included inside java.nio.channels
23.
24. Sample code for Asynchronous I/O: Using Future FileSystem fs = FileSystems.getDefault(); Path path = fs.getPath ("/home/masoud/a.png"); AsynchronousFileChannel ch = AsynchronousFileChannel.open (path); ByteBuffer buf = ByteBuffer.allocate (2048); Future<Integer> result = ch.read (buf,0); while (!result.isDone ()) { System.out.println ("Doing something else"); Thread.sleep (500); } System.out.println ("Bytes we read: "+result.get ()); ch.close (); The Future object allows us to check on the status of the asynchronous job when we want to get back at it.
25. Sample code for Asynchronous I/O: Using Callback Path path = Paths.get("/home/masoud/series.txt"); AsynchronousFileChannel ch = AsynchronousFileChannel.open(path); final ByteBuffer buf = ByteBuffer.allocate(2048); ch.read(buf, 0, buf, new SimpleHandler()); class SimpleHandler implements CompletionHandler<Integer, ByteBuffer> { public void completed(Integer result, ByteBuffer attachment) { System.out.println(new String(attachment.array())); } public void failed(Throwable th, ByteBuffer attachment) { System.out.println(th.toString()); } } interface CompletionHandler<V,A> Attachment is something to carry a context object into the handler. Value number of bytes we read or write. read(ByteBuffer dst, long position, A attachment, CompletionHandler<Integer,? super A> handler) interface CompletionHandler<V,A> Attachment is something to carry a context object into the handler. Value number of bytes we read or write.
26.
27. Other JSR 203 features The java.io.File.getPath() method File type MIME detection using Files.probeContentType