List of usage examples for java.nio.file Files walkFileTree
public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException
From source file:com.cloudbees.clickstack.util.Files2.java
/** * Update file and dir permissions./*from ww w . j a va 2 s .c om*/ * * @param path * @param filePermissions * @param dirPermissions * @throws RuntimeIOException */ private static void chmodAddPermissions(@Nonnull Path path, @Nonnull final Set<PosixFilePermission> filePermissions, @Nonnull final Set<PosixFilePermission> dirPermissions) throws RuntimeIOException { if (!Files.exists(path)) { throw new IllegalArgumentException("Given path " + path + " does not exist"); } SimpleFileVisitor<Path> setReadOnlyFileVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isDirectory(file)) { throw new IllegalStateException("No dir expected here: " + file); } else { Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file); Files.setPosixFilePermissions(file, Sets.union(existingPermissions, filePermissions)); } return super.visitFile(file, attrs); } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(dir); Files.setPosixFilePermissions(dir, Sets.union(existingPermissions, dirPermissions)); return super.preVisitDirectory(dir, attrs); } }; try { Files.walkFileTree(path, setReadOnlyFileVisitor); } catch (IOException e) { throw new RuntimeIOException("Exception setting permissions file permissions to " + filePermissions + " and folder permissions to " + dirPermissions + " on " + path, e); } }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeUnusedPrograms(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("programs"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override/*from w ww.j a va2 s .c o m*/ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (!activeProgIds.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Unused '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d unused program(s).", i[0])); }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeIgnoredStations(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("schedules"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override// w w w . j a v a2 s . c o m public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (stationList != null && !stationList.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Remove '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d ignored station(s).", i[0])); }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Cleans the Workspace of the AUT and creates a demo Project. * //from w w w . ja v a 2 s . c o m * @throws IOException * on reset the workspace. * @throws URISyntaxException * on reset the workspace. */ private void prepareAUTWorkspace() throws IOException, URISyntaxException { File wsPathFile = new File(getWorkspacePath()); Path wsPath = wsPathFile.toPath(); if (wsPathFile.exists()) { Files.walkFileTree(wsPath, getDeleteFileVisitor()); LOGGER.info("Removed AUT_WS: " + getWorkspacePath()); } Files.createDirectory(wsPath); Map<String, String> env = new HashMap<String, String>(); env.put("create", "true"); FileSystem fs = FileSystems.newFileSystem(getClass().getResource("/DemoWebTests.zip").toURI(), env); Iterable<Path> rootDirectories = fs.getRootDirectories(); for (Path root : rootDirectories) { DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root); for (Path path : directoryStream) { if (path.getFileName().startsWith("DemoWebTests.zip")) { LOGGER.info("Found DemoWebTest."); Files.copy(path, Paths.get(wsPath.toString(), "DemoWebTests.zip")); URI uriDemoZip = new URI("jar:" + Paths.get(wsPath.toString(), "/DemoWebTests.zip").toUri()); LOGGER.info(uriDemoZip); FileSystem zipFs = FileSystems.newFileSystem(uriDemoZip, env); copyFolder(zipFs.getPath("/"), Paths.get(getWorkspacePath())); zipFs.close(); } } } fs.close(); LOGGER.info("Created Demoproject in: " + getWorkspacePath()); }
From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.FsCrawlerImplAllParametersIT.java
/** * Test case for #95: https://github.com/dadoonet/fscrawler/issues/95 : Folder index is not getting delete on delete of folder *//*from w w w.ja v a2 s . c om*/ @Test public void test_remove_folder_deleted_enabled() throws Exception { Fs fs = startCrawlerDefinition().setRemoveDeleted(true).build(); startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null); // We should have 7 docs first countTestHelper(getCrawlerName(), null, 7, currentTestResourceDir); logContentOfDir(currentTestResourceDir, Level.DEBUG); // We remove a directory logger.info(" ---> Removing dir subdir1"); Files.walkFileTree(currentTestResourceDir.resolve("subdir1"), 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; } }); logContentOfDir(currentTestResourceDir, Level.DEBUG); // We expect to have 4 docs now countTestHelper(getCrawlerName(), null, 4, currentTestResourceDir); }
From source file:org.tinymediamanager.core.Utils.java
/** * Deletes a complete directory recursively, using Java NIO * // w w w .j a va 2 s. c om * @param dir * directory to delete * @throws IOException */ public static void deleteDirectoryRecursive(Path dir) throws IOException { if (!Files.exists(dir)) { return; } LOGGER.info("Deleting complete directory: " + dir); Files.walkFileTree(dir, new FileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { LOGGER.warn("Could not delete " + file + "; " + exc.getMessage()); return FileVisitResult.CONTINUE; } }); }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
/** * Modifies given allFiles object to include all files given by the incl pattern * /*from w w w . j a v a 2 s. co m*/ * Semantics: Add all files from localRoot to allFiles matching the pattern */ private void handleInclude(final Include incl, final Path localRoot, final Set<Path> allFiles) { final PathMatcher pathMatcher = localRoot.getFileSystem().getPathMatcher("glob:" + incl.getPattern()); try { Files.walkFileTree(localRoot, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relFile = localRoot.relativize(file); if (pathMatcher.matches(relFile)) { allFiles.add(file); } return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (pathMatcher.matches(dir)) { Set<Path> filesToAdd = CSARImporter.this.getAllFiles(dir); allFiles.addAll(filesToAdd); return SKIP_SUBTREE; } else { return CONTINUE; } } }); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
/** * Lists all files contained in the given path *///www .j av a2 s .c om private Set<Path> getAllFiles(Path startPath) { final Set<Path> res = new HashSet<>(); try { Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { res.add(file); return CONTINUE; } }); } catch (IOException e) { throw new IllegalStateException(e); } return res; }
From source file:org.tinymediamanager.core.Utils.java
/** * Unzips the specified zip file to the specified destination directory. Replaces any files in the destination, if they already exist. * /*from w w w.j av a 2 s.co m*/ * @param zipFile * the name of the zip file to extract * @param destDir * the directory to unzip to * @throws IOException */ public static void unzip(Path zipFile, final Path destDir) { Map<String, String> env = new HashMap<>(); try { // if the destination doesn't exist, create it if (!Files.exists(destDir)) { Files.createDirectories(destDir); } // check if file exists env.put("create", String.valueOf(!Files.exists(zipFile))); // use a Zip filesystem URI URI fileUri = zipFile.toUri(); // here URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null); try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) { final Path root = zipfs.getPath("/"); // walk the zip file tree and copy files to the destination Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { final Path destFile = Paths.get(destDir.toString(), file.toString()); LOGGER.debug("Extracting file {} to {}", file, destFile); Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final Path dirToCreate = Paths.get(destDir.toString(), dir.toString()); if (!Files.exists(dirToCreate)) { LOGGER.debug("Creating directory {}", dirToCreate); Files.createDirectory(dirToCreate); } return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("Failed to create zip file!" + e.getMessage()); } }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
@Override public InputStream getStream() { //// w w w. ja va 2 s .c o m // Grab our working repository // final Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath(); Path workspacePath = ((XacmlAdminUI) getUI()).getUserWorkspace(); final Path tarFile = Paths.get(workspacePath.toString(), "Repository.tgz"); try (OutputStream os = Files.newOutputStream(tarFile)) { try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(os)) { try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzOut)) { tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); Files.walkFileTree(repoPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.getFileName().toString().startsWith(".git")) { return FileVisitResult.SKIP_SUBTREE; } Path relative = repoPath.relativize(dir); if (relative.toString().isEmpty()) { return super.preVisitDirectory(dir, attrs); } TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); tarOut.putArchiveEntry(entry); tarOut.closeArchiveEntry(); return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".xml") == false) { return super.visitFile(file, attrs); } Path relative = repoPath.relativize(file); TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); entry.setSize(Files.size(file)); tarOut.putArchiveEntry(entry); try { IOUtils.copy(Files.newInputStream(file), tarOut); } catch (IOException e) { logger.error(e); } tarOut.closeArchiveEntry(); return super.visitFile(file, attrs); } }); tarOut.finish(); } } } catch (IOException e) { logger.error(e); } try { return Files.newInputStream(tarFile); } catch (IOException e) { logger.error(e); } return null; }