Java Code Examples for java.nio.file.Files.walkFileTree()

The following are Jave code examples for showing how to use walkFileTree() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Elasticsearch   File: LogConfigurator.java   Source Code and License Vote up 10 votes
static void resolveConfig(Environment env, final Settings.Builder settingsBuilder) {

        try {
            Files.walkFileTree(env.configFile(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileName = file.getFileName().toString();
                    if (fileName.startsWith("logging.")) {
                        for (String allowedSuffix : ALLOWED_SUFFIXES) {
                            if (fileName.endsWith(allowedSuffix)) {
                                loadConfig(file, settingsBuilder);
                                break;
                            }
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException ioe) {
            throw new ElasticsearchException("Failed to load logging configuration", ioe);
        }
    }
 
Example 2
Project: hippo-groovy-updater   File: TestMavenPlugin.java   Source Code and License Vote up 7 votes
public void compareFolders(File expected, File result) throws IOException {
    final CollectFilesVisitor visitor = new CollectFilesVisitor();
    List<Path> resultFilesPaths = new ArrayList<>();
    List<Path> resultFoldersPaths = new ArrayList<>();

    visitor.setCollectedFilesList(resultFilesPaths);
    visitor.setCollectedFoldersList(resultFoldersPaths);

    Files.walkFileTree(result.toPath(), visitor);

    List<Path> expectedFilePaths = new ArrayList<>();
    List<Path> expectedFolderPaths = new ArrayList<>();
    visitor.setCollectedFilesList(expectedFilePaths);
    visitor.setCollectedFoldersList(expectedFolderPaths);

    Files.walkFileTree(expected.toPath(), visitor);

    logger.info("comparing {} paths", expectedFilePaths.size());
    assertContentCompares(expectedFilePaths, resultFilesPaths);
    assertNameCompares(expectedFolderPaths, resultFoldersPaths);

}
 
Example 3
Project: BIMplatform   File: PathUtils.java   Source Code and License Vote up 7 votes
public static void removeDirectoryWithContent(Path directory) throws IOException {
	if (Files.isDirectory(directory)) {
		Files.walkFileTree(directory, 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 exc) throws IOException {
				Files.delete(dir);
				return FileVisitResult.CONTINUE;
			}
		});
	}
}
 
Example 4
Project: omero-ms-queue   File: ClassPathFactory.java   Source Code and License Vote up 6 votes
/**
 * Builds a class path with all the files selected by the given predicate 
 * in the specified base directory and, recursively, in all of its 
 * sub-directories.
 * @param dir the directory in which to find the (jar) files.
 * @param select tests whether or not to include a regular file.
 * @return the class path.
 * @throws NullPointerException if the argument is {@code null}.
 * @throws IOException if an I/O error occurs while trawling the directory.
 */
public static ClassPath fromDir(Path dir, Predicate<Path> select) 
        throws IOException {
    requireNonNull(dir, "dir");
    requireNonNull(select, "select");
    
    ClassPath cp = new ClassPath();
    
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attrs) throws IOException {
            if (attrs.isRegularFile() && select.test(file)) {
                cp.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    
    return cp;
}
 
Example 5
Project: chipKIT-importer   File: ChipKitProjectImporter.java   Source Code and License Vote up 6 votes
private void importSketchFiles( Path sketchDirPath ) throws IOException {
    if ( !copyingFiles ) return;
    Files.walkFileTree(sketchDirPath, new CopyingFileVisitor(sketchDirPath, getSourceFilesDirectoryPath(), PROJECT_SOURCE_FILE_MATCHER) {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            if ( file.toString().endsWith(".ino.cpp") ) {
                String filename = file.getFileName().toString();
                String newFilename = filename.replace(".ino.cpp", ".cpp");
                Path targetFilePath = target.resolve( source.relativize( Paths.get(file.getParent().toString(), newFilename) ) );
                copyFile( file, targetFilePath );
                try {
                    removeLineDirectives( targetFilePath);
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            } else { 
                copyFile( file, target.resolve( source.relativize(file) ) );
            }
            return CONTINUE;
        }            
    });
}
 
Example 6
Project: HardVox   File: ChunkDataStore.java   Source Code and License Vote up 6 votes
@Override
public void close() {
    memory.clear();
    try {
        Files.walkFileTree(tmpDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.deleteIfExists(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.deleteIfExists(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 7
Project: bazel-tools   File: PathUtils.java   Source Code and License Vote up 6 votes
public static void removeRecursive(final Path path) throws IOException {
  Files.walkFileTree(
      path,
      new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
            throws IOException {
          Files.deleteIfExists(file);
          return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
            throws IOException {
          Files.deleteIfExists(dir);
          return FileVisitResult.CONTINUE;
        }
      });
}
 
Example 8
Project: Hollow-Knight-SaveManager   File: Listeners.java   Source Code and License Vote up 6 votes
public static void deleteFiles (String path){    
	 try {
		 Path directory = Paths.get(path);
		 Files.walkFileTree(directory, 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 exc) throws IOException {
		        Files.delete(dir);
		        return FileVisitResult.CONTINUE;
		    }
		 });
	} catch (IOException e) {
		e.printStackTrace();
	}      
}
 
Example 9
Project: launcher-backend   File: FileUploadHelper.java   Source Code and License Vote up 6 votes
/**
 * Deletes a directory recursively
 *
 * @param directory
 * @return true if deletion succeeds, false otherwise
 */
public static boolean deleteDirectory(Path directory) {
    if (directory != null) {
        try {
            Files.walkFileTree(directory, 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 exc) throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException ignored) {
            return false;
        }
    }
    return true;
}
 
Example 10
Project: openjdk-jdk10   File: SourcePathTest.java   Source Code and License Vote up 6 votes
/**
 * This method is primarily used to give visual confirmation that a test case
 * generated files when the compilation succeeds and so generates no other output,
 * such as error messages.
 */
List<Path> showFiles(Path dir) throws IOException {
    List<Path> files = new ArrayList<>();
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if (Files.isRegularFile(file)) {
                out.println("Found " + file);
                files.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    return files;
}
 
Example 11
Project: rs-aggregator   File: FileCleanerTest.java   Source Code and License Vote up 5 votes
@Test
@Ignore("Assumes non-existing directory")
public void testCleaner() throws Exception {
  Set<File> fileSet = new HashSet<>();
  fileSet.add(new File("/Users/ecco/git/rs-aggregator/target/test-output/synchronizer/zandbak11.dans.knaw.nl/ehri2/mdx/__SOR__/ehri2/tmp/rs/collection2/folder1/doc1.txt"));
  fileSet.add(new File("/Users/ecco/git/rs-aggregator/target/test-output/synchronizer/zandbak11.dans.knaw.nl/ehri2/mdx/__SOR__/ehri2/tmp/rs/collection2/folder1/doc2.txt"));
  FileCleaner cleaner = new FileCleaner(fileSet);
  Path startingDir = Paths.get("target/test-output/synchronizer/zandbak11.dans.knaw.nl/ehri2/mdx/__SOR__");
  Files.walkFileTree(startingDir, cleaner);
}
 
Example 12
Project: jdk8u-jdk   File: WsImportTest.java   Source Code and License Vote up 5 votes
private static void deleteGeneratedFiles() {
    Path p = Paths.get("generated");
    if (Files.exists(p)) {
        try {
            Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file,
                                                 BasicFileAttributes attrs) throws IOException {

                    Files.delete(file);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                                                          IOException exc) throws IOException {

                    if (exc == null) {
                        Files.delete(dir);
                        return CONTINUE;
                    } else {
                        throw exc;
                    }
                }
            });
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
 
Example 13
Project: cljbuck   File: FindFilesTask.java   Source Code and License Vote up 5 votes
private boolean receive(final Object o) throws IOException {
    tracer.info(started(hashCode).toString());
    if (o instanceof Closer) {
        tracer.info(finished(hashCode).toString());
        return true;
    }
    final Glob glob = (Glob) o;
    final PathTraversal pathTraversal = PathTraversal.create(glob.glob, out, workspacePath);
    Files.walkFileTree(Paths.get(glob.start), pathTraversal);
    tracer.info(finished(hashCode).toString());
    return false;
}
 
Example 14
Project: ArchUnit   File: ClassFileSource.java   Source Code and License Vote up 5 votes
FromFilePath(Path path, ImportOptions importOptions) {
    this.importOptions = importOptions;
    if (path.toFile().exists()) {
        try {
            Files.walkFileTree(path, this);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 15
Project: neoscada   File: Executables.java   Source Code and License Vote up 5 votes
public static void setAllExecutable ( final Path directory, final boolean state ) throws IOException
{
    Files.walkFileTree ( directory, new SimpleFileVisitor<Path> () {
        @Override
        public FileVisitResult visitFile ( final Path file, final BasicFileAttributes attrs ) throws IOException
        {
            if ( Files.isRegularFile ( file, LinkOption.NOFOLLOW_LINKS ) )
            {
                setExecutable ( file, state );
            }
            return super.visitFile ( file, attrs );
        }
    } );
}
 
Example 16
Project: openjdk-jdk10   File: Test.java   Source Code and License Vote up 5 votes
private static void deleteGeneratedFiles() {
    Path p = Paths.get("..", "classes", "javax", "xml", "ws", "xsanymixed", "org");
    System.out.println("performing cleanup, deleting wsdl compilation result: " + p.toFile().getAbsolutePath());
    if (Files.exists(p)) {
        try {
            Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(
                        Path file,
                        BasicFileAttributes attrs) throws IOException {

                    System.out.println("deleting file [" + file.toFile().getAbsoluteFile() + "]");
                    Files.delete(file);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(
                        Path dir,
                        IOException exc) throws IOException {

                    System.out.println("deleting dir [" + dir.toFile().getAbsoluteFile() + "]");
                    if (exc == null) {
                        Files.delete(dir);
                        return CONTINUE;
                    } else {
                        throw exc;
                    }
                }
            });
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
 
Example 17
Project: Java-9-Programming-Blueprints   File: FindFileTask.java   Source Code and License Vote up 5 votes
@Override
public void run() {
    final EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        Files.walkFileTree(startDir, this);
        transaction.commit();
    } catch (IOException ex) {
        transaction.rollback();
    }
}
 
Example 18
Project: chipKIT-importer   File: ArduinoBuilderRunner.java   Source Code and License Vote up 4 votes
private List <Path> findAuxLibraryPaths(ChipKitBoardConfig config, GCCToolFinder toolFinder, List<Path> mainLibraries) throws IOException {
    LOGGER.info("Looking for additional library paths");
    
    // TODO: Consider expanding the list of valid library source file extensions
    final PathMatcher librarySourceMatcher = FileSystems.getDefault().getPathMatcher("glob:*.{c,cpp}");
    final Path gccPath = toolFinder.findTool( LanguageTool.CCCompiler );
    final Path corePath = config.getCoreDirPath();
    final Path variantPath = config.getVariantDirPath();
    
    final List <Path> allLibraries = new ArrayList<>(mainLibraries);
    final List <Path> ret = new ArrayList<>();

    for (int i = 0; i < allLibraries.size(); i++) {
        Path libDir = allLibraries.get(i);
        final Path librariesDir = libDir.getParent();
        Files.walkFileTree(libDir, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (Files.isDirectory(file)) {
                    return CONTINUE;
                }
                if (!librarySourceMatcher.matches(file.getFileName())) {
                    return CONTINUE;
                }

                try {
                    new NativeProcessRunner( m -> {                            
                        if ( m.startsWith("--") ) {
                            LOGGER.info(m);
                            return;
                        } else if (m.startsWith(" ")) {                                
                            String path = m.trim();
                            if ( path.endsWith("\\") ) {
                                path = path.substring(0, path.length()-2).trim();
                            }
                            Path dependencyFilePath = Paths.get( path );
                            // TODO: If the "path" string does not represent a path then it probably contains error information. Find a way to handle it. 
                            if ( Files.exists( dependencyFilePath ) ) {
                                LOGGER.info( "Dependency path: " + dependencyFilePath );
                                if ( dependencyFilePath.startsWith( librariesDir ) ) {
                                    Path relativeDependencyPath = librariesDir.relativize(dependencyFilePath.normalize());
                                    String libraryName = relativeDependencyPath.getName(0).toString();                                    
                                    Path libraryPath = librariesDir.resolve(libraryName);                                    
                                    if ( !allLibraries.contains(libraryPath) ) {
                                        LOGGER.info("Found library path: " + libraryPath);
                                        allLibraries.add(libraryPath);
                                        ret.add(libraryPath);
                                    }
                                } else {
                                    LOGGER.info( "Ignoring dependency file path:" + dependencyFilePath );
                                }
                            }
                        }
                    }).runNativeProcess( createDependencyResolutionCommand( gccPath, corePath, variantPath, mainLibraries, file ) );
                } catch ( Exception ex ) {
                    LOGGER.log( Level.SEVERE, "Failed to resolve additional dependencies for " + file.toAbsolutePath().toString(), ex );
                }

                return CONTINUE;
            }
        });
    }
    
    return ret;
}
 
Example 19
Project: jfrog-idea-plugin   File: NpmPackageFileFinder.java   Source Code and License Vote up 4 votes
/**
 * Get package.json directories and their application names.
 * @return List of package.json's parent directories.
 */
public List<String> getPackageFilePairs() throws IOException {
    Files.walkFileTree(projectPath, this);
    return applicationPaths;
}
 
Example 20
Project: tabularius   File: NumbersFileWalker.java   Source Code and License Vote up 4 votes
public NumbersFileWalker(String path) throws IOException {
	basePath = path;
	Files.walkFileTree(Paths.get(path), this);
}