Skip to content

Instantly share code, notes, and snippets.

@cesarvasconcelos
Last active January 30, 2019 21:58
Show Gist options
  • Save cesarvasconcelos/e18b378bcb6a881635c6ac4ac3b3168a to your computer and use it in GitHub Desktop.
Save cesarvasconcelos/e18b378bcb6a881635c6ac4ac3b3168a to your computer and use it in GitHub Desktop.

Revisions

  1. cesarvasconcelos revised this gist Jan 30, 2019. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -101,6 +101,13 @@ public static void main( String[] args ) throws IOException
    System.out.println("Arquivos dentro de " + pathFiles.toAbsolutePath() );
    streamFiles.filter( path -> path.toFile().isFile() ).forEach( System.out::println );

    // novo método Java 8 Files.walk() com Stream<T>
    // visitar toda a sub-árvore de diretórios.
    // A listagem aqui é recursiva
    Stream<Path> streamFilesDirRecursive = Files.walk( pathFiles );
    System.out.println("Listagem recursiva dentro de " + pathFiles.toAbsolutePath() );
    streamFilesDirRecursive.forEach( System.out::println );


    // observando/capturando mudanças em arquivos de diretórios
    try ( WatchService watchService = FileSystems.getDefault().newWatchService() )
  2. cesarvasconcelos revised this gist Jan 30, 2019. 1 changed file with 15 additions and 29 deletions.
    44 changes: 15 additions & 29 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,3 @@



    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    @@ -78,7 +75,7 @@ public static void main( String[] args ) throws IOException
    System.out.println( file.toRealPath( LinkOption.NOFOLLOW_LINKS ) );
    } else System.out.println( "Nenhum arquivo foi encontrado." );

    // novo método Files.lines() com Stream<T>
    // novo método Java 8 Files.lines() com Stream<T>
    // Read all lines from a file as a Stream
    Stream<String> stream = Files.lines( pathBackupHamlet );

    @@ -92,7 +89,18 @@ public static void main( String[] args ) throws IOException
    // número de ocorrências
    long count = Files.lines( pathBackupHamlet ).filter( predicate ).count();
    System.out.println( String.format( "Foram encontradas %d ocorrências do termo \'%s\' no arquivo %s",
    count, searchString, pathBackupHamlet.getFileName() ) );
    count, searchString, pathBackupHamlet.getFileName() ) );

    // novo método Java 8 Files.list() com Stream<T>
    // return the Stream containing the elements of which are the entries in the directory.
    // The listing is not recursive.
    Stream<Path> streamFilesDir = Files.list( pathFiles );
    Stream<Path> streamFiles = Files.list( pathFiles );
    System.out.println("Diretórios dentro de " + pathFiles.toAbsolutePath() );
    streamFilesDir.filter( path -> path.toFile().isDirectory() ).forEach( System.out::println );
    System.out.println("Arquivos dentro de " + pathFiles.toAbsolutePath() );
    streamFiles.filter( path -> path.toFile().isFile() ).forEach( System.out::println );


    // observando/capturando mudanças em arquivos de diretórios
    try ( WatchService watchService = FileSystems.getDefault().newWatchService() )
    @@ -174,8 +182,8 @@ private static void writeLine( Path pathDestino, String line )
    try
    {
    Files.write( pathDestino, line.getBytes(), StandardOpenOption.CREATE,
    StandardOpenOption.WRITE,
    StandardOpenOption.APPEND );
    StandardOpenOption.WRITE,
    StandardOpenOption.APPEND );
    } catch ( IOException e )
    {
    e.printStackTrace();
    @@ -245,26 +253,4 @@ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws

    return new MyFileFinder();
    }

    private static class WriteToFile {
    private BufferedWriter bufferedWriter;
    private String str;

    public WriteToFile( BufferedWriter bufferedWriter, String str )
    {
    this.bufferedWriter = bufferedWriter;
    this.str = str;
    }

    public void invoke()
    {
    try
    {
    bufferedWriter.write( str );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }
    }
    }
  3. cesarvasconcelos revised this gist Jan 30, 2019. 1 changed file with 56 additions and 2 deletions.
    58 changes: 56 additions & 2 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@



    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    @@ -59,7 +60,7 @@ public static void main( String[] args ) throws IOException
    // lendo e escrevendo em arquivos texto
    Path pathBackupHamlet = Paths.get( "files/backup_hamlet.xml" );
    Path pathDestino = Paths.get( "files/backup02_hamlet.xml" );
    copiarArquivoTexto( pathBackupHamlet.toString(), pathDestino.toString() );
    copiarArquivoTextoComStreams( pathBackupHamlet.toString(), pathDestino.toString() );

    // percorrendo diretórios
    Path pathFiles = Paths.get( "files" );
    @@ -127,9 +128,11 @@ public static void main( String[] args ) throws IOException

    static void copiarArquivoTexto( String origem, String destino )
    {

    Path pathOrigem = Paths.get( origem );
    Path pathDestino = Paths.get( destino );

    // Java 7: try-with-resources
    try ( BufferedReader bufferedReader = Files.newBufferedReader( pathOrigem, StandardCharsets.UTF_8 );
    BufferedWriter bufferedWriter = Files.newBufferedWriter( pathDestino, StandardCharsets.UTF_8,
    StandardOpenOption.CREATE,
    @@ -141,14 +144,43 @@ static void copiarArquivoTexto( String origem, String destino )
    {
    bufferedWriter.write( line ); // ou write(line, 0, line.lenght())
    }

    bufferedWriter.flush();
    System.out.println( "Terminado!" );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }
    static void copiarArquivoTextoComStreams( String origem, String destino )
    {

    Path pathOrigem = Paths.get( origem );
    Path pathDestino = Paths.get( destino );

    // Java 7: try-with-resources
    // Java 8: Stream & File.lines(path) method
    try ( Stream<String> streamLines = Files.lines( pathOrigem ) )
    {
    streamLines.forEach( line -> writeLine( pathDestino, line ) );
    System.out.println( "Terminado!" );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }

    private static void writeLine( Path pathDestino, String line )
    {
    try
    {
    Files.write( pathDestino, line.getBytes(), StandardOpenOption.CREATE,
    StandardOpenOption.WRITE,
    StandardOpenOption.APPEND );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }

    // útil para percorrer diretórios
    static SimpleFileVisitor<Path> getMyFileVisitor()
    @@ -213,4 +245,26 @@ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws

    return new MyFileFinder();
    }

    private static class WriteToFile {
    private BufferedWriter bufferedWriter;
    private String str;

    public WriteToFile( BufferedWriter bufferedWriter, String str )
    {
    this.bufferedWriter = bufferedWriter;
    this.str = str;
    }

    public void invoke()
    {
    try
    {
    bufferedWriter.write( str );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }
    }
    }
  4. cesarvasconcelos revised this gist Nov 26, 2018. No changes.
  5. cesarvasconcelos revised this gist Nov 26, 2018. 1 changed file with 22 additions and 3 deletions.
    25 changes: 22 additions & 3 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    package br.edu.ifpb;


    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    @@ -9,6 +9,9 @@
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Optional;
    import java.util.function.Predicate;
    import java.util.stream.Stream;

    public class NIOTest {

    @@ -74,6 +77,22 @@ public static void main( String[] args ) throws IOException
    System.out.println( file.toRealPath( LinkOption.NOFOLLOW_LINKS ) );
    } else System.out.println( "Nenhum arquivo foi encontrado." );

    // novo método Files.lines() com Stream<T>
    // Read all lines from a file as a Stream
    Stream<String> stream = Files.lines( pathBackupHamlet );

    String searchString = "Hamlet";
    Predicate<String> predicate = s -> s.contains( searchString );
    // retorna Optional<String> que *pode ou não* conter uma string
    Optional<String> first = stream.filter( predicate ).findFirst();
    if ( first.isPresent() )
    System.out.println( String.format( "O termo \'%s\' foi encontrado no arquivo %s", searchString, pathBackupHamlet.getFileName() ) );
    else System.out.println( String.format( "O termo \'%s\' não foi encontrado" ) );
    // número de ocorrências
    long count = Files.lines( pathBackupHamlet ).filter( predicate ).count();
    System.out.println( String.format( "Foram encontradas %d ocorrências do termo \'%s\' no arquivo %s",
    count, searchString, pathBackupHamlet.getFileName() ) );

    // observando/capturando mudanças em arquivos de diretórios
    try ( WatchService watchService = FileSystems.getDefault().newWatchService() )
    {
    @@ -89,7 +108,7 @@ public static void main( String[] args ) throws IOException

    do
    {
    watchKey = watchService.take();
    watchKey = watchService.take(); // fica em espera por um evento
    Path eventDir = keyMap.get( watchKey );

    for ( WatchEvent<?> event : watchKey.pollEvents() )
    @@ -194,4 +213,4 @@ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws

    return new MyFileFinder();
    }
    }
    }
  6. cesarvasconcelos revised this gist Nov 20, 2018. 1 changed file with 35 additions and 2 deletions.
    37 changes: 35 additions & 2 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -7,6 +7,8 @@
    import java.nio.file.*;
    import java.nio.file.attribute.BasicFileAttributes;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;

    public class NIOTest {

    @@ -63,14 +65,45 @@ public static void main( String[] args ) throws IOException

    // encontrando arquivos particulares
    ArrayList<Path> encontrados = new ArrayList<>();
    SimpleFileVisitor<Path> ff = getMyFileFinder( "*.txt", encontrados );
    SimpleFileVisitor<Path> ff = getMyFileFinder( "*.xml", encontrados );
    Files.walkFileTree( pathFiles, ff );
    System.out.println( "Encontrados: " );
    if ( encontrados.size() > 0 )
    {
    for ( Path file : encontrados )
    System.out.println( file.toRealPath( LinkOption.NOFOLLOW_LINKS ) );
    } else System.out.println( "Nenhum arquivo foi encontrado." );

    // observando/capturando mudanças em arquivos de diretórios
    try ( WatchService watchService = FileSystems.getDefault().newWatchService() )
    {

    // registrando os tipos de eventos que quero escutar e sobre quem
    Map<WatchKey, Path> keyMap = new HashMap<>();
    keyMap.put( pathFiles.register( watchService,
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_DELETE,
    StandardWatchEventKinds.ENTRY_MODIFY ), pathFiles );

    WatchKey watchKey;

    do
    {
    watchKey = watchService.take();
    Path eventDir = keyMap.get( watchKey );

    for ( WatchEvent<?> event : watchKey.pollEvents() )
    {
    WatchEvent.Kind<?> kind = event.kind();
    Path eventPath = ( Path ) event.context();
    System.out.println( eventDir + ": " + kind + " : " + eventPath );

    }
    } while ( watchKey.reset() );
    } catch ( Exception e )
    {
    System.out.println( e.getMessage() );
    }
    }

    static void copiarArquivoTexto( String origem, String destino )
    @@ -141,9 +174,9 @@ public FileVisitResult visitFileFailed( Path file, IOException exc ) throws IOEx
    return new MyFileVisitor();
    }

    // útil para encontrar arquivos
    static SimpleFileVisitor<Path> getMyFileFinder( String padrão, ArrayList<Path> encontrados )
    {

    class MyFileFinder extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException
  7. cesarvasconcelos revised this gist Nov 20, 2018. 1 changed file with 87 additions and 4 deletions.
    91 changes: 87 additions & 4 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,11 @@
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.*;
    import java.nio.file.attribute.BasicFileAttributes;
    import java.util.ArrayList;

    public class NIOTest {

    public static void main( String[] args ) throws IOException
    {

    @@ -40,7 +43,7 @@ public static void main( String[] args ) throws IOException
    Files.deleteIfExists( cópia );

    // criar diretório
    Path pasta = Paths.get( "files", "pasta" );
    Path pasta = Paths.get( "files", "novaPasta" );
    Files.createDirectory( pasta );

    // mover
    @@ -49,9 +52,25 @@ public static void main( String[] args ) throws IOException
    Files.move( pathHamlet, pasta.resolve( pathHamlet.getFileName() ), StandardCopyOption.REPLACE_EXISTING );

    // lendo e escrevendo em arquivos texto
    Path pathBackupHamlet = Paths.get( "files/backup_hamlet.xml" ) ;
    Path pathDestino = Paths.get( "files/backup02_hamlet.xml" ) ;
    Path pathBackupHamlet = Paths.get( "files/backup_hamlet.xml" );
    Path pathDestino = Paths.get( "files/backup02_hamlet.xml" );
    copiarArquivoTexto( pathBackupHamlet.toString(), pathDestino.toString() );

    // percorrendo diretórios
    Path pathFiles = Paths.get( "files" );
    SimpleFileVisitor<Path> fv = getMyFileVisitor();
    Files.walkFileTree( pathFiles, fv );

    // encontrando arquivos particulares
    ArrayList<Path> encontrados = new ArrayList<>();
    SimpleFileVisitor<Path> ff = getMyFileFinder( "*.txt", encontrados );
    Files.walkFileTree( pathFiles, ff );
    System.out.println( "Encontrados: " );
    if ( encontrados.size() > 0 )
    {
    for ( Path file : encontrados )
    System.out.println( file.toRealPath( LinkOption.NOFOLLOW_LINKS ) );
    } else System.out.println( "Nenhum arquivo foi encontrado." );
    }

    static void copiarArquivoTexto( String origem, String destino )
    @@ -72,10 +91,74 @@ static void copiarArquivoTexto( String origem, String destino )
    }

    bufferedWriter.flush();
    System.out.println("Terminado!");
    System.out.println( "Terminado!" );
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }

    // útil para percorrer diretórios
    static SimpleFileVisitor<Path> getMyFileVisitor()
    {
    class MyFileVisitor extends SimpleFileVisitor<Path> {

    @Override
    public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) throws IOException
    {
    System.out.println( "Pronto para visitar: " + dir.toString() );
    return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory( Path dir, IOException exc ) throws IOException
    {
    System.out.println( "Acabou de visitar: " + dir.toString() );
    return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException
    {
    if ( attrs.isRegularFile() )
    {
    System.out.print( "Arquivo: " );
    }
    System.out.println( file );

    return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed( Path file, IOException exc ) throws IOException
    {
    System.err.println( exc.getMessage() );

    return FileVisitResult.CONTINUE;
    }
    } // classe interna local

    return new MyFileVisitor();
    }

    static SimpleFileVisitor<Path> getMyFileFinder( String padrão, ArrayList<Path> encontrados )
    {

    class MyFileFinder extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException
    {
    Path name = file.getFileName();
    PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher( "glob:" + padrão );

    System.out.println( "Verificando " + name );
    if ( pathMatcher.matches( name ) )
    encontrados.add( file );

    return FileVisitResult.CONTINUE;
    }
    } // classe interna local

    return new MyFileFinder();
    }
    }
  8. cesarvasconcelos created this gist Nov 18, 2018.
    81 changes: 81 additions & 0 deletions NIOTest.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    package br.edu.ifpb;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.*;

    public class NIOTest {
    public static void main( String[] args ) throws IOException
    {

    Path pathHamlet = Paths.get( "files", "hamlet.xml" );
    Path pathInexistente = Paths.get( "files/arquivo-inexistente.txt" );

    System.out.println( pathHamlet.getFileName() );
    System.out.println( pathHamlet.toString() );
    System.out.println( pathHamlet.getNameCount() );
    System.out.println( pathHamlet.getName( 0 ) );
    System.out.println( pathHamlet.getName( pathHamlet.getNameCount() - 1 ) ); // o último
    System.out.println( pathHamlet.toAbsolutePath() );
    System.out.println( pathHamlet.toRealPath( LinkOption.NOFOLLOW_LINKS ) );

    System.out.println();

    // métodos funcionam mesmo se arquivo não existir
    System.out.println( pathInexistente.getFileName() );
    System.out.println( pathInexistente.toString() );
    System.out.println( pathInexistente.getNameCount() );
    System.out.println( pathInexistente.getName( 0 ) );
    System.out.println( pathInexistente.getName( pathInexistente.getNameCount() - 1 ) ); // o último
    System.out.println( pathInexistente.toAbsolutePath() );
    //System.out.println( pathInexistente.toRealPath( LinkOption.NOFOLLOW_LINKS ) ); // tem de existir, senão exceção

    // copiar
    Path cópia = Paths.get( "files", "novo_hamlet.xml" );
    Files.copy( pathHamlet, cópia, StandardCopyOption.REPLACE_EXISTING );

    // apagar
    Files.deleteIfExists( cópia );

    // criar diretório
    Path pasta = Paths.get( "files", "pasta" );
    Files.createDirectory( pasta );

    // mover
    // o resolve() receberá o arquivo computará o novo path resultante
    // ou seja, "files/pasta/hamlet.xml"
    Files.move( pathHamlet, pasta.resolve( pathHamlet.getFileName() ), StandardCopyOption.REPLACE_EXISTING );

    // lendo e escrevendo em arquivos texto
    Path pathBackupHamlet = Paths.get( "files/backup_hamlet.xml" ) ;
    Path pathDestino = Paths.get( "files/backup02_hamlet.xml" ) ;
    copiarArquivoTexto( pathBackupHamlet.toString(), pathDestino.toString() );
    }

    static void copiarArquivoTexto( String origem, String destino )
    {
    Path pathOrigem = Paths.get( origem );
    Path pathDestino = Paths.get( destino );

    try ( BufferedReader bufferedReader = Files.newBufferedReader( pathOrigem, StandardCharsets.UTF_8 );
    BufferedWriter bufferedWriter = Files.newBufferedWriter( pathDestino, StandardCharsets.UTF_8,
    StandardOpenOption.CREATE,
    StandardOpenOption.WRITE,
    StandardOpenOption.TRUNCATE_EXISTING ); )
    {
    String line;
    while ( ( line = bufferedReader.readLine() ) != null )
    {
    bufferedWriter.write( line ); // ou write(line, 0, line.lenght())
    }

    bufferedWriter.flush();
    System.out.println("Terminado!");
    } catch ( IOException e )
    {
    e.printStackTrace();
    }
    }
    }