Last active
January 30, 2019 21:58
-
-
Save cesarvasconcelos/e18b378bcb6a881635c6ac4ac3b3168a to your computer and use it in GitHub Desktop.
Exemplos com java.nio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.BufferedReader; | |
| import java.io.BufferedWriter; | |
| import java.io.IOException; | |
| import java.nio.charset.StandardCharsets; | |
| import java.nio.file.*; | |
| import java.nio.file.attribute.BasicFileAttributes; | |
| 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 { | |
| 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", "novaPasta" ); | |
| 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" ); | |
| copiarArquivoTextoComStreams( 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( "*.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." ); | |
| // 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 ); | |
| 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() ) ); | |
| // 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 ); | |
| // 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() ) | |
| { | |
| // 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(); // fica em espera por um evento | |
| 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 ) | |
| { | |
| 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, | |
| 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(); | |
| } | |
| } | |
| 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() | |
| { | |
| 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(); | |
| } | |
| // ú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 | |
| { | |
| 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(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment