SlideShare une entreprise Scribd logo
1  sur  29
NIO.2: The I/O API For Future Masoud Kalali [email_address] Twitter: @MasoudKalali http://kalali.me
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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
Comparing I/O before Java 7 and Java 7: Basic Features Before Java 7 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],What NIO.2 provides Java 7 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Current lacking IO features
Comparing I/O before Java 7 and Java 7: Advanced Features ,[object Object],[object Object],[object Object],[object Object],Current lacking IO features Before Java 7 ,[object Object],[object Object],[object Object],[object Object],What NIO.2 provides Java 7
The NIO.2 Architecture ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],A FileSystem A FileSystemsProvider WatchService Attibutes Path FileStore Etc Through FileSystems Factory class
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
Basic File operations with Path ,[object Object],[object Object],[object Object],[object Object],FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath("/home/masoud/simple.txt"); Path newCopy = fs.getPath("/home/masoud/copy of simple.txt"); p.copyTo(newCopy, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); newCopy.moveTo(fs.getPath("/home/masoud/moved.txt"), StandardCopyOption.ATOMIC_MOVE);
Symbolic links support ,[object Object],[object Object],[object Object],FileSystem fs = FileSystems.getDefault(); Path actualFile = fs.getPath("/home/masoud/simple"); //creating a symbolic link Path symLinkFile = fs.getPath("/home/masoud/simple.sym"); symLinkFile.createSymbolicLink(actualFile); System.out.println("Getting the link target: "+symLinkFile.readSymbolicLink()); //Creating hard link Path linkFile = fs.getPath("/home/masoud/simple.link"); linkFile.createLink(actualFile);
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(&quot;/home/masoud/&quot;); 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
File attributes and metadata ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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(&quot;/home/masoud/simple&quot;); BasicFileAttributeView bav= p.getFileAttributeView(BasicFileAttributeView.class,   LinkOption.NOFOLLOW_LINKS); BasicFileAttributes ba =bav.readAttributes(); System.out.println(p.toString() + &quot; last access:  &quot; + ba.lastAccessTime()); System.out.println(p.toString() + &quot; last modified: &quot; + ba.lastModifiedTime());
File attributes and metadata: Platform specific Attributes PosixFileAttributeView Extends BasicFileAttributeView,  contain Posix specific attributes. FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath(&quot;/home/masoud/photo.png&quot;); Set<String> supportedViews = fs.supportedFileAttributeViews(); if (supportedViews.contains(&quot;unix&quot;)) { 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.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Different ways for retrieving file attributes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],BasicFileAttributeView DosFileAttributeView PosixFileAttributeView
File attributes and metadata:  Managing POSIX files permissions  ,[object Object],[object Object],[object Object],[object Object],FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath(&quot;/home/masoud/script.sh&quot;); PosixFileAttributes patts = Attributes.readPosixFileAttributes(p, LinkOption.NOFOLLOW_LINKS); Set<PosixFilePermission> st = patts.permissions(); System.out.println(PosixFilePermissions.toString(st));
//Setting permissions Set<PosixFilePermission> st = PosixFilePermissions.fromString(&quot;rwxrwxrwx&quot;); Attributes.setPosixFilePermissions(p, st2); //Setting the owner username, we should find the user prior to using Attributes utility class UserPrincipal up = s.getUserPrincipalLookupService().lookupPrincipalByName(&quot;masoud&quot;); 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
FileStore features The  FileStore : Represent the file system underlying storage devices, pools, partitions, and so on. FileSystem fs = FileSystems.getFileSystem(new URI(&quot;File:///&quot;)); Path p = fs.getPath(&quot;/home/masoud&quot;); 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(&quot;  device  size(MB)  used(MB)  available(MB) &quot;); System.out.format(&quot;%-20s %12d %12d %12d%n&quot;, fstore, total, used, avail); We can use FileSystem.getFileStores() to get all underlying file stores.
FileSystem fs = FileSystems.getDefault(); Path p = fs.getPath(&quot;/usr/bin&quot;); DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { public boolean accept(Path file) throws IOException { String perm = PosixFilePermissions.toString(Attributes.readPosixFileAttributes(file).permissions());   if (perm.equalsIgnoreCase(&quot;rwxr-xr-x&quot;))  return true;   return false; } }; DirectoryStream<Path> ds = p.newDirectoryStream(filter); for (Path p : ds) { System.out.println(p); } Directory content stream ,[object Object],[object Object],[object Object]
File system change notification ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Change notification: Sample Code FileSystem fs = FileSystems.getDefault(); WatchService ws = fs.newWatchService(); Path path = fs.getPath(&quot;/home/masoud/Pictures&quot;); path.register(ws, StandardWatchEventKind.ENTRY_CREATE,    StandardWatchEventKind.ENTRY_DELETE); WatchKey key = ws.take(); List<WatchEvent<?>> events = key.pollEvents(); for (WatchEvent object : events) { if (object.kind() == StandardWatchEventKind.ENTRY_DELETE) { System.out.println(&quot;Delete: &quot; +  path.toRealPath(true)+&quot;/&quot;+ object.context().toString()); } if (object.kind() == StandardWatchEventKind.ENTRY_CREATE) { System.out.println(&quot;Created: &quot; +  path.toRealPath(true)+&quot;/&quot;+ object.context().toString()); } }
Provider interface ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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
Asynchronous I/O for sockets and Files ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Sample code for Asynchronous I/O: Using Future FileSystem fs = FileSystems.getDefault(); Path path = fs.getPath (&quot;/home/masoud/a.png&quot;); AsynchronousFileChannel ch = AsynchronousFileChannel.open (path); ByteBuffer buf = ByteBuffer.allocate (2048); Future<Integer> result = ch.read (buf,0); while (!result.isDone ()) { System.out.println (&quot;Doing something else&quot;); Thread.sleep (500); } System.out.println (&quot;Bytes we read: &quot;+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.
Sample code for Asynchronous I/O: Using Callback Path path = Paths.get(&quot;/home/masoud/series.txt&quot;); 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.
Different types of Asynchronous channels AsynchronousChannel AsynchronousByteChannel AsynchronousFileChannel ,[object Object],[object Object],[object Object],[object Object],[object Object],AsynchronousSocketChannel ,[object Object],[object Object],[object Object],[object Object],[object Object],AsynchronousServerSocketChannel ,[object Object],[object Object],[object Object],[object Object],[object Object],AsynchronousDatagramChannel ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Other JSR 203 features The java.io.File.getPath() method File type MIME detection using  Files.probeContentType
More Information OpenJDK New I/O Project –  http://openjdk.java.net/projects/nio Questions?
Thank you Thank you for joining this session Masoud Kalali http://kalali.me Twitter: @MasoudKalali [email_address]

Contenu connexe

Tendances

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
The Ring programming language version 1.7 book - Part 29 of 196
The Ring programming language version 1.7 book - Part 29 of 196The Ring programming language version 1.7 book - Part 29 of 196
The Ring programming language version 1.7 book - Part 29 of 196Mahmoud Samir Fayed
 
Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++subham sahu
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to ProveKazuho Oku
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniquesjoaopmaia
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180Mahmoud Samir Fayed
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныTimur Safin
 
Unix Programming with Perl
Unix Programming with PerlUnix Programming with Perl
Unix Programming with PerlKazuho Oku
 
Penetration testing using python
Penetration testing using pythonPenetration testing using python
Penetration testing using pythonPurna Chander K
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanismYuki Nishiwaki
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniquesjoaopmaia
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014Henning Jacobs
 

Tendances (20)

Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
The Ring programming language version 1.7 book - Part 29 of 196
The Ring programming language version 1.7 book - Part 29 of 196The Ring programming language version 1.7 book - Part 29 of 196
The Ring programming language version 1.7 book - Part 29 of 196
 
Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++
 
Jug java7
Jug java7Jug java7
Jug java7
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to Prove
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180
 
Linux shell scripting
Linux shell scriptingLinux shell scripting
Linux shell scripting
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Inheritance
InheritanceInheritance
Inheritance
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
 
Unix Programming with Perl
Unix Programming with PerlUnix Programming with Perl
Unix Programming with Perl
 
Penetration testing using python
Penetration testing using pythonPenetration testing using python
Penetration testing using python
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanism
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 
Java File I/O
Java File I/OJava File I/O
Java File I/O
 

En vedette

アジャイルチームのためのソフトウェアテスト勉強会
アジャイルチームのためのソフトウェアテスト勉強会アジャイルチームのためのソフトウェアテスト勉強会
アジャイルチームのためのソフトウェアテスト勉強会Taisuke Shiratori
 
Eclipse modeling projectの概要
Eclipse modeling projectの概要Eclipse modeling projectの概要
Eclipse modeling projectの概要Shintaro Hosoai
 
Facebookのリアルタイム Big Data 処理
Facebookのリアルタイム Big Data 処理Facebookのリアルタイム Big Data 処理
Facebookのリアルタイム Big Data 処理maruyama097
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web FormsIlio Catallo
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
すしモデリング 20150917
すしモデリング 20150917すしモデリング 20150917
すしモデリング 20150917Iwao Harada
 
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジー
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジーDBTS2015 Tokyo DBAが知っておくべき最新テクノロジー
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジーMasaya Ishikawa
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The BasicsIlio Catallo
 
Reactive Programming
Reactive ProgrammingReactive Programming
Reactive Programmingmaruyama097
 
実践的な設計って、なんだろう?
実践的な設計って、なんだろう?実践的な設計って、なんだろう?
実践的な設計って、なんだろう?増田 亨
 
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3irof N
 
マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!mosa siru
 

En vedette (13)

アジャイルチームのためのソフトウェアテスト勉強会
アジャイルチームのためのソフトウェアテスト勉強会アジャイルチームのためのソフトウェアテスト勉強会
アジャイルチームのためのソフトウェアテスト勉強会
 
Eclipse modeling projectの概要
Eclipse modeling projectの概要Eclipse modeling projectの概要
Eclipse modeling projectの概要
 
Facebookのリアルタイム Big Data 処理
Facebookのリアルタイム Big Data 処理Facebookのリアルタイム Big Data 処理
Facebookのリアルタイム Big Data 処理
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web Forms
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
すしモデリング 20150917
すしモデリング 20150917すしモデリング 20150917
すしモデリング 20150917
 
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジー
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジーDBTS2015 Tokyo DBAが知っておくべき最新テクノロジー
DBTS2015 Tokyo DBAが知っておくべき最新テクノロジー
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Reactive Programming
Reactive ProgrammingReactive Programming
Reactive Programming
 
実践的な設計って、なんだろう?
実践的な設計って、なんだろう?実践的な設計って、なんだろう?
実践的な設計って、なんだろう?
 
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3
よくある業務開発の自動化事情 #jjug_ccc #ccc_cd3
 
マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!マイクロにしすぎた結果がこれだよ!
マイクロにしすぎた結果がこれだよ!
 
Culture
CultureCulture
Culture
 

Similaire à NIO.2, the I/O API for the future

Javase7 1641812
Javase7 1641812Javase7 1641812
Javase7 1641812Vinay H G
 
Building File Systems with FUSE
Building File Systems with FUSEBuilding File Systems with FUSE
Building File Systems with FUSEelliando dias
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and EnhancementsGagan Agrawal
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System InterfaceWayne Jones Jnr
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.pptHelalMirzad
 
WhatsNewNIO2.pdf
WhatsNewNIO2.pdfWhatsNewNIO2.pdf
WhatsNewNIO2.pdfMohit Kumar
 
File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdfSudhanshiBakre1
 
File system.
File system.File system.
File system.elyza12
 
Chapter07 Advanced File System Management
Chapter07      Advanced  File  System  ManagementChapter07      Advanced  File  System  Management
Chapter07 Advanced File System ManagementRaja Waseem Akhtar
 
Learn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptLearn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptgeethasenthil2706
 
Fuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientFuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientVishal Kanaujia
 
File Management – File Concept, access methods, File types and File Operation
File Management – File Concept, access methods,  File types and File OperationFile Management – File Concept, access methods,  File types and File Operation
File Management – File Concept, access methods, File types and File OperationDhrumil Panchal
 
Unit 3 chapter 1-file management
Unit 3 chapter 1-file managementUnit 3 chapter 1-file management
Unit 3 chapter 1-file managementKalai Selvi
 

Similaire à NIO.2, the I/O API for the future (20)

Javase7 1641812
Javase7 1641812Javase7 1641812
Javase7 1641812
 
Building File Systems with FUSE
Building File Systems with FUSEBuilding File Systems with FUSE
Building File Systems with FUSE
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System Interface
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
 
WhatsNewNIO2.pdf
WhatsNewNIO2.pdfWhatsNewNIO2.pdf
WhatsNewNIO2.pdf
 
CH11.pdf
CH11.pdfCH11.pdf
CH11.pdf
 
My History
My HistoryMy History
My History
 
File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdf
 
File system.
File system.File system.
File system.
 
Chapter07 Advanced File System Management
Chapter07      Advanced  File  System  ManagementChapter07      Advanced  File  System  Management
Chapter07 Advanced File System Management
 
Learn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptLearn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems ppt
 
History
HistoryHistory
History
 
Fuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientFuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficient
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
File system structure
File system structureFile system structure
File system structure
 
File Management – File Concept, access methods, File types and File Operation
File Management – File Concept, access methods,  File types and File OperationFile Management – File Concept, access methods,  File types and File Operation
File Management – File Concept, access methods, File types and File Operation
 
Ch10
Ch10Ch10
Ch10
 
Unit 3 chapter 1-file management
Unit 3 chapter 1-file managementUnit 3 chapter 1-file management
Unit 3 chapter 1-file management
 

Plus de Masoud Kalali

Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsMasoud Kalali
 
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EECON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EEMasoud Kalali
 
BOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectivelyBOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectivelyMasoud Kalali
 
Real-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and SolutionsReal-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and SolutionsMasoud Kalali
 
How to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themHow to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themMasoud Kalali
 
Confess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practiceConfess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practiceMasoud Kalali
 
Utilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE SecurityUtilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE SecurityMasoud Kalali
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
 
Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881Masoud Kalali
 
Security in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missingSecurity in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missingMasoud Kalali
 
An Overview of RUP methodology
An Overview of RUP methodologyAn Overview of RUP methodology
An Overview of RUP methodologyMasoud Kalali
 
An overview of software development methodologies.
An overview of software development methodologies.An overview of software development methodologies.
An overview of software development methodologies.Masoud Kalali
 

Plus de Masoud Kalali (13)

Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EECON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
 
BOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectivelyBOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectively
 
Real-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and SolutionsReal-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and Solutions
 
How to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themHow to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid them
 
Java EE 7 overview
Java EE 7 overviewJava EE 7 overview
Java EE 7 overview
 
Confess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practiceConfess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practice
 
Utilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE SecurityUtilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE Security
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881
 
Security in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missingSecurity in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missing
 
An Overview of RUP methodology
An Overview of RUP methodologyAn Overview of RUP methodology
An Overview of RUP methodology
 
An overview of software development methodologies.
An overview of software development methodologies.An overview of software development methodologies.
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(&quot;/home/masoud/simple.txt&quot;); 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(&quot;/home/masoud/&quot;); 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(&quot;/home/masoud/simple&quot;); BasicFileAttributeView bav= p.getFileAttributeView(BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); BasicFileAttributes ba =bav.readAttributes(); System.out.println(p.toString() + &quot; last access: &quot; + ba.lastAccessTime()); System.out.println(p.toString() + &quot; last modified: &quot; + 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(&quot;/home/masoud/photo.png&quot;); Set<String> supportedViews = fs.supportedFileAttributeViews(); if (supportedViews.contains(&quot;unix&quot;)) { 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(&quot;rwxrwxrwx&quot;); Attributes.setPosixFilePermissions(p, st2); //Setting the owner username, we should find the user prior to using Attributes utility class UserPrincipal up = s.getUserPrincipalLookupService().lookupPrincipalByName(&quot;masoud&quot;); 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(&quot;File:///&quot;)); Path p = fs.getPath(&quot;/home/masoud&quot;); 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(&quot; device size(MB) used(MB) available(MB) &quot;); System.out.format(&quot;%-20s %12d %12d %12d%n&quot;, fstore, total, used, avail); We can use FileSystem.getFileStores() to get all underlying file stores.
  • 18.
  • 19.
  • 20. Change notification: Sample Code FileSystem fs = FileSystems.getDefault(); WatchService ws = fs.newWatchService(); Path path = fs.getPath(&quot;/home/masoud/Pictures&quot;); path.register(ws, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_DELETE); WatchKey key = ws.take(); List<WatchEvent<?>> events = key.pollEvents(); for (WatchEvent object : events) { if (object.kind() == StandardWatchEventKind.ENTRY_DELETE) { System.out.println(&quot;Delete: &quot; + path.toRealPath(true)+&quot;/&quot;+ object.context().toString()); } if (object.kind() == StandardWatchEventKind.ENTRY_CREATE) { System.out.println(&quot;Created: &quot; + path.toRealPath(true)+&quot;/&quot;+ object.context().toString()); } }
  • 21.
  • 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 (&quot;/home/masoud/a.png&quot;); AsynchronousFileChannel ch = AsynchronousFileChannel.open (path); ByteBuffer buf = ByteBuffer.allocate (2048); Future<Integer> result = ch.read (buf,0); while (!result.isDone ()) { System.out.println (&quot;Doing something else&quot;); Thread.sleep (500); } System.out.println (&quot;Bytes we read: &quot;+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(&quot;/home/masoud/series.txt&quot;); 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
  • 28. More Information OpenJDK New I/O Project – http://openjdk.java.net/projects/nio Questions?
  • 29. Thank you Thank you for joining this session Masoud Kalali http://kalali.me Twitter: @MasoudKalali [email_address]