SlideShare une entreprise Scribd logo
Java 7
           Asynchronous I/O (NIO2)

                               Julien Buret
                            Séven Le Mesle



vendredi 29 juillet 2011
Asynchronous I/O API
           Comparaison avec les autres API I/O


                Socket             SocketChannel   AsyncSocketC
                                                   hannel
                       Java 1.0     Java 1.4
                                                    Java 1.7
                       Synchrone    Synchone
                                                    Asynchrone
                       Bloquant     Non
                                    bloquant        Non
                                                    bloquant
                                    Reactor
                                    pattern         Proactor
                                                    pattern
                                    Notification
vendredi 29 juillet 2011
Asynchronous I/O API
           Comparaison avec les autres API I/O


  FileOutputStream
                               FileChannel           AsynchronousFileChannel
    FileInputStream



      OutputStream
                              SocketChannel        AsynchronousSocketChannel
        InputStream



      OutputStream
                           ServerSocketChannel   AsynchronousServerSocketChannel
        InputStream


     Java 1.0                 Java 1.4                    Java 1.7

vendredi 29 juillet 2011
Asynchronous I/O API
           Créer un channel

      AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(4,
      threadFactory);
      AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open
      (channelGroup);
      socketChannel.bind(new InetSocketAddress(8080));
      Future<AsynchronousSocketChannel> resAccept = socketChannel.accept();
      Future<Integer> res = resAccept.get().read(ByteBuffer.allocate(512));




vendredi 29 juillet 2011
Asynchronous I/O API
           Concept : Future
                 Future<Integer> result = channel.read(byteBuffer);

                       Retourne un «Future» avec le nombre d’octet lue (ou écrit)

                 result.get();

                       Attend la fin de l’opération I/O

                 result.get(5, TimeUnit.SECONDS);

                       Attend avec un timout

                 result.isDone();

                       Verifie si l’appel est terminé




vendredi 29 juillet 2011
Asynchronous I/O API
           Concept : CompletionHandler

           channelToClient.read(buffer, counter, new CompletionHandler<Integer,
           AtomicInteger>() {

                 public void completed(final Integer result, final AtomicInteger counter){
                    handlerThreadPool.submit(new Runnable() {
                        public void run() {
                           readComplete(result, counter, buffer, channelToClient);
                        }
                    });
                 }

                 public void failed(Throwable exc, AtomicInteger counter) {
                    logger.error("Client {} failed to read", counter, exc);
                 }
           });




vendredi 29 juillet 2011
Threading model

                 AsynchronousChannelGroup
                       Encapsule le pool de thread, la file d’attente et les
                       autres ressources partagées par les sockets
                       2 implémentations
                           Fixed thread pool
                           Cached thread pool (ou thread pool fournit)



vendredi 29 juillet 2011
Threading model
           Fixed thread pool


                                             CompletionHandler




                           I/O internal
                                          Thread   Thread   Thread




vendredi 29 juillet 2011
Threading model
           Cached thread pool

                                      CompletionHandler


                                    Thread       Thread       Thread                 Cached Thread pool




                     I/O internal
                                        Thread       Thread            Internal Thread pool
                                                                       1 ou sun.nio.ch.internalThreadPoolSize




vendredi 29 juillet 2011
Threading model
                 FixedThreadPool              CachedThreadPool ou
                                              ThreadPool fournit
                       Thread partagé entre
                       I/O et callback         Un pool de thread
                                               pour l’I/O et un autre
                       Eviter la contention
                                               pour les callback
                       dans les callback
                                               Attention au context
                                               switch




vendredi 29 juillet 2011
Bench


                       Sur une VM 2vCPU (client et serveur)
                           4000 req/s (50Ko/req et 50Ko/resp)
                           200 Mo/s (Reçu et émis)




vendredi 29 juillet 2011
Multicast non bloquant

       NetworkInterface eth0Itf = NetworkInterface.getByName("eth0");
                  InetAddress mcGroup = InetAddress.getByName("225.0.0.100");

                       DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
                               .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                               .bind(new InetSocketAddress(5000))
                               .setOption(StandardSocketOptions.IP_MULTICAST_IF, eth0Itf);

                       MembershipKey key = dc.join(mcGroup, eth0Itf);

                       Selector selector = Selector.open();
                       dc.register(selector, dc.validOps());




vendredi 29 juillet 2011
Multicast non bloquant
           while (true) {
                  selector.select();
                 Iterator it = selector.selectedKeys().iterator();

                     while (it.hasNext()) {
                        SelectionKey selKey = (SelectionKey) it.next();
                        it.remove();
                        if (selKey.isValid() && selKey.isReadable()) {
                            DatagramChannel sChannel = (DatagramChannel) selKey.channel();
                        }
                        if (selKey.isValid() && selKey.isWritable()) {
                            DatagramChannel sChannel = (DatagramChannel) selKey.channel();
                        }
                        }
       }




vendredi 29 juillet 2011
Le reste
                 Mise à jour des API SocketChannel
                       bind(SocketAdress local)
                       setOption(SocketOption name, T Value)
                 Support de SCTP (Protocole de transport réseau)
                 IPV6 sous Windows
                 Support de SDP sous Solaris (protocole RMDA utilisé
                 par Infiniband)


vendredi 29 juillet 2011
File extension
                 Traitement Asynchrone
                 Droits POSIX / ACL NFS / DOS / ...
                 Liens symboliques et vérous
                 Système de fichier et partitions
                 Supervision d’activité sur répertoires et fichiers
                 Parcours de répertoire
                 Méthodes utilitaires


vendredi 29 juillet 2011
java.nio.Path
                 = java.io.File
                 file.toPath() - path.toFile()
                 chemin système du fichier
                            Path p = Paths.get(“/home/user/.myApp“);

                            Iterator<Path> it = p.iterator(); // elements

                            p.relativize(Paths.get(“/home/john“)); // “../john“

                            p.normalize(); // /home/john/../user = /home/user

                            p.startsWith(“/home“);


vendredi 29 juillet 2011
AsynchronousFileChannel
                 Traitement asynchrone non bloquant
                       Chaque read/write donne la position dans le fichier
                       Accède a plusieurs parties du fichier en parallèle
                 Threadsafe
                 Supporte les Locks
                 Options définies sur open(...)



vendredi 29 juillet 2011
AsynchronousFileChannel
              AsynchronousFileChannel afc = AsynchronousFileChannel.open(path,
              StandardOpenOption.CREATE);

              FileLock lock = afc.lock().get();

              afc.write(buffer, 0l).get();
               // Buffer wrote to file

              lock.close();
              afc.close();




vendredi 29 juillet 2011
Files operations
                 Files fournit des utilitaires (guava / commons-io)
                       copy / move / delete /...
                       read* / write / newReader* / newWriter*
                       temp dirs / symlinks / walkFileTree
                 Et les accès systèmes
                       set or get : owner / attribute / posixFilePermissions
                       FileSystem / FileStore


vendredi 29 juillet 2011
FileAttributes
                 Lecture et modification des atributs du fichier
                       BasicFileAttributes, PosixFileAttributes, Dos, ...

                    Path p = Paths.get(“/home/user/.myApp“);

                    BasicFileAttributes attr = Files.readAttributes(file,BasicFileAttributes.class);

                    System.out.println("creationTime: " + attr.creationTime());
                    System.out.println("lastAccessTime: " + attr.lastAccessTime());
                    System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

                    System.out.println("isDirectory: " + attr.isDirectory());
                    System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
                    System.out.println("size: " + attr.size());

                    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
                    FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
                    Files.setPosixFilePermissions(file, perms);

vendredi 29 juillet 2011
WatchService

                 Comme un Selector pour les Paths
                       WatchKey k = register(path, event, ...);
                       WatchEvent evt = k.pollEvents();
                       Reset key
                 Boucle infini et Threading à la charge du développeur




vendredi 29 juillet 2011
WatchService
              Path p = Paths.get(“/home/user/.myApp“);

              WatchService watcher = FileSystems.getDefault().newWatchService();
              WatchKey key = p.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

              for (;;) {
                 key = watcher.take();
                 for (WatchEvent<?> event: key.pollEvents()) {
              	      WatchEvent.Kind<?> kind = event.kind();

              	        WatchEvent<Path> ev = (WatchEvent<Path>)event;
              	        Path filename = ev.context();
              	        //....
                  }
                  boolean valid = key.reset();
                  if (!valid) {
                       break;
                  }
              }




vendredi 29 juillet 2011
DirectoryStream

                 Autorise le forEach() sur les entrées d’un répertoire
                       Glob pattern (“*.java“)
                       RegExp
                       Filtre implémenté
              DirectoryStream<Path> ds = Files.newDirectoryStream(dir, “*.java“);

              for(Path p : ds){
                // ...
              }




vendredi 29 juillet 2011
FileVisitor

                 Files.walkFileTree parcours l’arborescence
                       utilise un FileVisitor
                       Définit des options (FOLLOW_LINKS, ... )
                 FileVisitor est invoqué pour chaque entrée
                       Permet de modifier le parcours
                       Fourni des callbacks pre/post visit File / Directory



vendredi 29 juillet 2011
FileVisitor
                   Path start = ...
                   Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                       @Override
                       public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
                       {
                         Files.delete(file);
                         return FileVisitResult.CONTINUE;
                       }
                       @Override
                       public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException
                       {
                         if (e == null) {
                             Files.delete(dir);
                             return FileVisitResult.CONTINUE;
                         } else {
                             // directory iteration failed
                             throw e;
                         }
                       }
                   });



vendredi 29 juillet 2011

Contenu connexe

PPTX
ILLUMINA SEQUENCE.pptx
PPT
Dna sequencing methods
PPTX
Sanger sequencing
PPT
Polymerase Chain Reaction
PPTX
Gene manipulation
PPTX
Screening of genomic library and expressed genes
PDF
Single Nucleotide Polymorphism Analysis (SNPs)
PPTX
Preparation and isolation of genomic
ILLUMINA SEQUENCE.pptx
Dna sequencing methods
Sanger sequencing
Polymerase Chain Reaction
Gene manipulation
Screening of genomic library and expressed genes
Single Nucleotide Polymorphism Analysis (SNPs)
Preparation and isolation of genomic

Tendances (20)

PPTX
R Gene Expression and Transcription Profiling
PPTX
next generation sequencing
PPTX
Rna isolatn
PPT
Nanobiotechnology lecture 2
PPTX
Dna sequencing
PPTX
Southern & Northern blot
PPT
Genetics chapter 7 dna structure and replication
PPTX
Whole genome sequence.
PPT
Dna History And Replication Review
PPTX
RFLP ,RAPD ,AFLP, STS, SCAR ,SSCP & QTL
PPT
Native American Mitochondrial Haplogroup Discoveries
PPTX
Ppt snp detection
PPT
DNA_Extraction_Overview
PPTX
Status and prospects of association mapping in crop plants
PDF
Impact des violences sexuelles de l'enfance à l'âge adulte (2015) - Mémoire T...
PPTX
Molecular RNA Probe
PPT
Dna Extraction Principles
PPTX
Mutation detection - M.V.MALA
PPTX
Gene Transformation Techniques
PPTX
Restriction Fragment Length Polymorphism (RFLP)
R Gene Expression and Transcription Profiling
next generation sequencing
Rna isolatn
Nanobiotechnology lecture 2
Dna sequencing
Southern & Northern blot
Genetics chapter 7 dna structure and replication
Whole genome sequence.
Dna History And Replication Review
RFLP ,RAPD ,AFLP, STS, SCAR ,SSCP & QTL
Native American Mitochondrial Haplogroup Discoveries
Ppt snp detection
DNA_Extraction_Overview
Status and prospects of association mapping in crop plants
Impact des violences sexuelles de l'enfance à l'âge adulte (2015) - Mémoire T...
Molecular RNA Probe
Dna Extraction Principles
Mutation detection - M.V.MALA
Gene Transformation Techniques
Restriction Fragment Length Polymorphism (RFLP)
Publicité

En vedette (6)

PPTX
PDF
JAVA NIO
PDF
Netty
PDF
The Proactor Pattern
PDF
KEY
Non blocking io with netty
JAVA NIO
Netty
The Proactor Pattern
Non blocking io with netty
Publicité

Similaire à Java Nio 2 (20)

PDF
Chap7 java net
PDF
PPT
Le Réseau et Java
PDF
Les socket ing1_issat
PDF
S1.4- Java ME.pdfS1.4- Java ME.pdfS1.4- Java ME.pdfS1.4- Java ME.pdf
PDF
Programmation concurrente en Java
PDF
Chapitre -6-Programmation Réseaux (Les sockets).pdf
PDF
RAPPORT DU PREMIER MINI PROJET «FORUM DE CHAT» Novembre 2005.pdf
PDF
02 java-socket
PPTX
Du hard et des réseaux: Les outils pour construire l'internet des objets chez...
PDF
log file sous Netbeans et J2ME
PPTX
Java SE 7
PPTX
Formation Google App Engine
PPTX
Formation1 sockets
ODP
Java 7 - Fork/Join
PDF
Introduction à Play Framework 2
PDF
La plateforme de services dynamiques OSGi
PPT
PFEs SagemCom
PPTX
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Chap7 java net
Le Réseau et Java
Les socket ing1_issat
S1.4- Java ME.pdfS1.4- Java ME.pdfS1.4- Java ME.pdfS1.4- Java ME.pdf
Programmation concurrente en Java
Chapitre -6-Programmation Réseaux (Les sockets).pdf
RAPPORT DU PREMIER MINI PROJET «FORUM DE CHAT» Novembre 2005.pdf
02 java-socket
Du hard et des réseaux: Les outils pour construire l'internet des objets chez...
log file sous Netbeans et J2ME
Java SE 7
Formation Google App Engine
Formation1 sockets
Java 7 - Fork/Join
Introduction à Play Framework 2
La plateforme de services dynamiques OSGi
PFEs SagemCom
Nio sur Netty par Mouhcine Moulou - 3 avril 2014

Plus de Publicis Sapient Engineering (20)

PDF
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
PDF
Xebicon'18 - IoT: From Edge to Cloud
PDF
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
PDF
XebiCon'18 - Modern Infrastructure
PDF
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
PDF
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
PDF
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
PDF
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
PDF
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
PDF
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
PDF
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
PDF
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
PDF
XebiCon'18 - Le développeur dans la Pop Culture
PDF
XebiCon'18 - Architecturer son application mobile pour la durabilité
PDF
XebiCon'18 - Sécuriser son API avec OpenID Connect
PDF
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
PDF
XebiCon'18 - Spark NLP, un an après
PDF
XebiCon'18 - La sécurité, douce illusion même en 2018
PDF
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
PDF
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
Xebicon'18 - IoT: From Edge to Cloud
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
XebiCon'18 - Modern Infrastructure
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
XebiCon'18 - Le développeur dans la Pop Culture
XebiCon'18 - Architecturer son application mobile pour la durabilité
XebiCon'18 - Sécuriser son API avec OpenID Connect
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
XebiCon'18 - Spark NLP, un an après
XebiCon'18 - La sécurité, douce illusion même en 2018
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...

Java Nio 2

  • 1. Java 7 Asynchronous I/O (NIO2) Julien Buret Séven Le Mesle vendredi 29 juillet 2011
  • 2. Asynchronous I/O API Comparaison avec les autres API I/O Socket SocketChannel AsyncSocketC hannel Java 1.0 Java 1.4 Java 1.7 Synchrone Synchone Asynchrone Bloquant Non bloquant Non bloquant Reactor pattern Proactor pattern Notification vendredi 29 juillet 2011
  • 3. Asynchronous I/O API Comparaison avec les autres API I/O FileOutputStream FileChannel AsynchronousFileChannel FileInputStream OutputStream SocketChannel AsynchronousSocketChannel InputStream OutputStream ServerSocketChannel AsynchronousServerSocketChannel InputStream Java 1.0 Java 1.4 Java 1.7 vendredi 29 juillet 2011
  • 4. Asynchronous I/O API Créer un channel AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(4, threadFactory); AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open (channelGroup); socketChannel.bind(new InetSocketAddress(8080)); Future<AsynchronousSocketChannel> resAccept = socketChannel.accept(); Future<Integer> res = resAccept.get().read(ByteBuffer.allocate(512)); vendredi 29 juillet 2011
  • 5. Asynchronous I/O API Concept : Future Future<Integer> result = channel.read(byteBuffer); Retourne un «Future» avec le nombre d’octet lue (ou écrit) result.get(); Attend la fin de l’opération I/O result.get(5, TimeUnit.SECONDS); Attend avec un timout result.isDone(); Verifie si l’appel est terminé vendredi 29 juillet 2011
  • 6. Asynchronous I/O API Concept : CompletionHandler channelToClient.read(buffer, counter, new CompletionHandler<Integer, AtomicInteger>() { public void completed(final Integer result, final AtomicInteger counter){ handlerThreadPool.submit(new Runnable() { public void run() { readComplete(result, counter, buffer, channelToClient); } }); } public void failed(Throwable exc, AtomicInteger counter) { logger.error("Client {} failed to read", counter, exc); } }); vendredi 29 juillet 2011
  • 7. Threading model AsynchronousChannelGroup Encapsule le pool de thread, la file d’attente et les autres ressources partagées par les sockets 2 implémentations Fixed thread pool Cached thread pool (ou thread pool fournit) vendredi 29 juillet 2011
  • 8. Threading model Fixed thread pool CompletionHandler I/O internal Thread Thread Thread vendredi 29 juillet 2011
  • 9. Threading model Cached thread pool CompletionHandler Thread Thread Thread Cached Thread pool I/O internal Thread Thread Internal Thread pool 1 ou sun.nio.ch.internalThreadPoolSize vendredi 29 juillet 2011
  • 10. Threading model FixedThreadPool CachedThreadPool ou ThreadPool fournit Thread partagé entre I/O et callback Un pool de thread pour l’I/O et un autre Eviter la contention pour les callback dans les callback Attention au context switch vendredi 29 juillet 2011
  • 11. Bench Sur une VM 2vCPU (client et serveur) 4000 req/s (50Ko/req et 50Ko/resp) 200 Mo/s (Reçu et émis) vendredi 29 juillet 2011
  • 12. Multicast non bloquant NetworkInterface eth0Itf = NetworkInterface.getByName("eth0"); InetAddress mcGroup = InetAddress.getByName("225.0.0.100"); DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET) .setOption(StandardSocketOptions.SO_REUSEADDR, true) .bind(new InetSocketAddress(5000)) .setOption(StandardSocketOptions.IP_MULTICAST_IF, eth0Itf); MembershipKey key = dc.join(mcGroup, eth0Itf); Selector selector = Selector.open(); dc.register(selector, dc.validOps()); vendredi 29 juillet 2011
  • 13. Multicast non bloquant while (true) { selector.select(); Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isReadable()) { DatagramChannel sChannel = (DatagramChannel) selKey.channel(); } if (selKey.isValid() && selKey.isWritable()) { DatagramChannel sChannel = (DatagramChannel) selKey.channel(); } } } vendredi 29 juillet 2011
  • 14. Le reste Mise à jour des API SocketChannel bind(SocketAdress local) setOption(SocketOption name, T Value) Support de SCTP (Protocole de transport réseau) IPV6 sous Windows Support de SDP sous Solaris (protocole RMDA utilisé par Infiniband) vendredi 29 juillet 2011
  • 15. File extension Traitement Asynchrone Droits POSIX / ACL NFS / DOS / ... Liens symboliques et vérous Système de fichier et partitions Supervision d’activité sur répertoires et fichiers Parcours de répertoire Méthodes utilitaires vendredi 29 juillet 2011
  • 16. java.nio.Path = java.io.File file.toPath() - path.toFile() chemin système du fichier Path p = Paths.get(“/home/user/.myApp“); Iterator<Path> it = p.iterator(); // elements p.relativize(Paths.get(“/home/john“)); // “../john“ p.normalize(); // /home/john/../user = /home/user p.startsWith(“/home“); vendredi 29 juillet 2011
  • 17. AsynchronousFileChannel Traitement asynchrone non bloquant Chaque read/write donne la position dans le fichier Accède a plusieurs parties du fichier en parallèle Threadsafe Supporte les Locks Options définies sur open(...) vendredi 29 juillet 2011
  • 18. AsynchronousFileChannel AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.CREATE); FileLock lock = afc.lock().get(); afc.write(buffer, 0l).get(); // Buffer wrote to file lock.close(); afc.close(); vendredi 29 juillet 2011
  • 19. Files operations Files fournit des utilitaires (guava / commons-io) copy / move / delete /... read* / write / newReader* / newWriter* temp dirs / symlinks / walkFileTree Et les accès systèmes set or get : owner / attribute / posixFilePermissions FileSystem / FileStore vendredi 29 juillet 2011
  • 20. FileAttributes Lecture et modification des atributs du fichier BasicFileAttributes, PosixFileAttributes, Dos, ... Path p = Paths.get(“/home/user/.myApp“); BasicFileAttributes attr = Files.readAttributes(file,BasicFileAttributes.class); System.out.println("creationTime: " + attr.creationTime()); System.out.println("lastAccessTime: " + attr.lastAccessTime()); System.out.println("lastModifiedTime: " + attr.lastModifiedTime()); System.out.println("isDirectory: " + attr.isDirectory()); System.out.println("isSymbolicLink: " + attr.isSymbolicLink()); System.out.println("size: " + attr.size()); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); Files.setPosixFilePermissions(file, perms); vendredi 29 juillet 2011
  • 21. WatchService Comme un Selector pour les Paths WatchKey k = register(path, event, ...); WatchEvent evt = k.pollEvents(); Reset key Boucle infini et Threading à la charge du développeur vendredi 29 juillet 2011
  • 22. WatchService Path p = Paths.get(“/home/user/.myApp“); WatchService watcher = FileSystems.getDefault().newWatchService(); WatchKey key = p.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); for (;;) { key = watcher.take(); for (WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); WatchEvent<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); //.... } boolean valid = key.reset(); if (!valid) { break; } } vendredi 29 juillet 2011
  • 23. DirectoryStream Autorise le forEach() sur les entrées d’un répertoire Glob pattern (“*.java“) RegExp Filtre implémenté DirectoryStream<Path> ds = Files.newDirectoryStream(dir, “*.java“); for(Path p : ds){ // ... } vendredi 29 juillet 2011
  • 24. FileVisitor Files.walkFileTree parcours l’arborescence utilise un FileVisitor Définit des options (FOLLOW_LINKS, ... ) FileVisitor est invoqué pour chaque entrée Permet de modifier le parcours Fourni des callbacks pre/post visit File / Directory vendredi 29 juillet 2011
  • 25. FileVisitor Path start = ... Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } } }); vendredi 29 juillet 2011