List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor
protected SimpleFileVisitor()
From source file:it.polimi.diceH2020.SPACE4CloudWS.fileManagement.FileUtility.java
public boolean destroyDir(@NotNull File path) throws IOException { Path directory = path.toPath(); @Getter//ww w . j a v a 2s . co m @Setter class BooleanWrapper { boolean deleted; } BooleanWrapper status = new BooleanWrapper(); Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { status.setDeleted(policy.delete(file.toFile())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { status.setDeleted(policy.delete(dir.toFile())); return FileVisitResult.CONTINUE; } }); return status.isDeleted(); }
From source file:de.ingrid.interfaces.csw.tools.FileUtils.java
/** * Delete a file or directory specified by a {@link Path}. This method uses * the new {@link Files} API and allows to specify a regular expression to * remove only files that match that expression. * // w w w . java 2s . c om * @param path * @param pattern * @throws IOException */ public static void deleteRecursive(Path path, final String pattern) throws IOException { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern); if (!Files.exists(path)) return; Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // try to delete the file anyway, even if its attributes // could not be read, since delete-only access is // theoretically possible if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { if (matcher.matches(dir.getFileName())) { if (dir.toFile().list().length > 0) { // remove even if not empty FileUtils.deleteRecursive(dir); } else { Files.delete(dir); } } return FileVisitResult.CONTINUE; } else { // directory iteration failed; propagate exception throw exc; } } }); }
From source file:org.bonitasoft.console.common.server.page.CustomPageDependenciesResolver.java
private Map<String, byte[]> loadLibraries(final File customPageLibDirectory) { final Map<String, byte[]> result = new HashMap<String, byte[]>(); try {/*w ww .j a va 2 s. com*/ Files.walkFileTree(customPageLibDirectory.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { final File currentFile = file.toFile(); result.put(currentFile.getName(), readFileToByteArray(currentFile)); return super.visitFile(file, attrs); } }); } catch (final IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } return result; }
From source file:ru.histone.staticrender.StaticRender.java
public void renderSite(final Path srcDir, final Path dstDir) { log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString()); Path contentDir = srcDir.resolve("content/"); final Path layoutDir = srcDir.resolve("layouts/"); FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() { @Override//from w ww .j ava2s .co m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) { ArrayNode ast = null; try { ast = histone.parseTemplateToAST(new FileReader(file.toFile())); } catch (HistoneException e) { throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e); } final String fileName = file.getFileName().toString(); String layoutId = fileName.substring(0, fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1); layouts.put(layoutId, ast); if (log.isDebugEnabled()) { log.debug("Layout found id='{}', file={}", layoutId, file); } else { log.info("Layout found id='{}'", layoutId); } } else { final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri())); final Path resolvedFile = dstDir.resolve(relativeFileName); if (!resolvedFile.getParent().toFile().exists()) { Files.createDirectories(resolvedFile.getParent()); } Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING, LinkOption.NOFOLLOW_LINKS); } return FileVisitResult.CONTINUE; } }; FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Scanner scanner = new Scanner(file, "UTF-8"); scanner.useDelimiter("-----"); String meta = null; StringBuilder content = new StringBuilder(); if (!scanner.hasNext()) { throw new RuntimeException("Wrong format #1:" + file.toString()); } if (scanner.hasNext()) { meta = scanner.next(); } if (scanner.hasNext()) { content.append(scanner.next()); scanner.useDelimiter("\n"); } while (scanner.hasNext()) { final String next = scanner.next(); content.append(next); if (scanner.hasNext()) { content.append("\n"); } } Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta); String layoutId = metaYaml.get("layout"); if (!layouts.containsKey(layoutId)) { throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId)); } final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri())); final Path resolvedFile = dstDir.resolve(relativeFileName); if (!resolvedFile.getParent().toFile().exists()) { Files.createDirectories(resolvedFile.getParent()); } Writer output = new FileWriter(resolvedFile.toFile()); ObjectNode context = jackson.createObjectNode(); ObjectNode metaNode = jackson.createObjectNode(); context.put("content", content.toString()); context.put("meta", metaNode); for (String key : metaYaml.keySet()) { if (!key.equalsIgnoreCase("content")) { metaNode.put(key, metaYaml.get(key)); } } try { histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output); output.flush(); } catch (HistoneException e) { throw new RuntimeException("Error evaluating content: " + e.getMessage(), e); } finally { output.close(); } return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(layoutDir, layoutVisitor); Files.walkFileTree(contentDir, contentVisitor); } catch (Exception e) { throw new RuntimeException("Error during site render", e); } }
From source file:com.ignorelist.kassandra.steam.scraper.PathResolver.java
public Set<Path> findSharedConfig() throws IOException { Path base = findSteamBase().resolve("steam").resolve("userdata"); final Set<Path> paths = new HashSet<>(); Files.walkFileTree(base, new SimpleFileVisitor<Path>() { @Override/*from ww w.jav a2 s .c o m*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if ("sharedconfig.vdf".equals(file.getFileName().toString())) { paths.add(file); } return super.visitFile(file, attrs); } }); if (paths.isEmpty()) { throw new IllegalStateException("can't find sharedconfig.vdf"); } return paths; }
From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java
private void processArchive(final Path zipFile, final int batchSize) throws IOException { try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipFile, null)) { final List<BookEntry> bookEntries = new ArrayList<>(); Path root = zipFileSystem.getPath("/"); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override//from ww w. ja va2s. c o m public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.toString().contains("__MACOSX")) { return FileVisitResult.SKIP_SUBTREE; } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) { BookEntry bookEntry = new BookEntry().setUploader("admin"); for (Path path : directoryStream) { if (!Files.isDirectory(path)) { if (path.toString().contains(".opf")) { bookEntry = parseOPF(path, bookEntry); } if (path.toString().contains(".mobi")) { bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI"); } if (path.toString().contains(".epub")) { bookEntry.setEpub(Files.readAllBytes(path)); } if (path.toString().contains(".jpg")) { bookEntry.setCover(Files.readAllBytes(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200) .toOutputStream(output); bookEntry.setThumbnail(output.toByteArray()); bookEntry.setThumbnailGenerated("done"); } } } if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) { bookEntries.add(bookEntry); if (bookEntries.size() > batchSize) { logger.info("Adding " + bookEntries.size() + " Books..."); try { solrHandler.addBeans(bookEntries); } catch (SolrServerException ex) { logger.error(ex, ex); } bookEntries.clear(); } } } catch (IOException ex) { logger.error(ex, ex); } return super.preVisitDirectory(dir, attrs); } }); try { if (!bookEntries.isEmpty()) { logger.info("Adding " + bookEntries.size() + " Books..."); solrHandler.addBeans(bookEntries); } } catch (SolrServerException ex) { logger.error(ex, ex); } } finally { Files.delete(zipFile); } }
From source file:uk.nhs.fhir.util.FhirFileUtils.java
public static void deleteRecursive(Path f) { try {//from w w w. java 2s . co m Files.walkFileTree(f, 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) { logger.error("Caught exception trying to delete " + f.toString() + ".", e); } }
From source file:org.apdplat.superword.extract.HyphenExtractor.java
public static Map<String, AtomicInteger> parseZip(String zipFile) { Map<String, AtomicInteger> data = new HashMap<>(); LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override/*from w w w. ja v a 2s. co m*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info("?" + file); // ? Path temp = Paths.get("target/origin-html-temp.txt"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); Map<String, AtomicInteger> rs = parseFile(temp.toFile().getAbsolutePath()); rs.keySet().forEach(k -> { data.putIfAbsent(k, new AtomicInteger()); data.get(k).addAndGet(rs.get(k).get()); }); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } return data; }
From source file:illarion.compile.Compiler.java
private static void processFileMode(@Nonnull final CommandLine cmd) throws IOException { storagePaths = new EnumMap<>(CompilerType.class); String npcPath = cmd.getOptionValue('n'); if (npcPath != null) { storagePaths.put(CompilerType.easyNPC, Paths.get(npcPath)); }/* w w w . ja v a2 s .co m*/ String questPath = cmd.getOptionValue('q'); if (questPath != null) { storagePaths.put(CompilerType.easyQuest, Paths.get(questPath)); } for (String file : cmd.getArgs()) { Path path = Paths.get(file); if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { FileVisitResult result = super.visitFile(file, attrs); if (result == FileVisitResult.CONTINUE) { processPath(file); return FileVisitResult.CONTINUE; } return result; } }); } else { processPath(path); } } }
From source file:org.ng200.openolympus.FileAccess.java
public static void deleteDirectoryByWalking(final Path path) throws IOException { if (!Files.exists(path)) { return;// w w w . jav a2 s . c o m } FileAccess.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException { if (e == null) { FileAccess.delete(dir); return FileVisitResult.CONTINUE; } else { throw e; } } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { FileAccess.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) throws IOException { FileAccess.delete(file); return FileVisitResult.CONTINUE; } }); Files.deleteIfExists(path); }