List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor
protected SimpleFileVisitor()
From source file:org.apdplat.superword.extract.PhraseExtractor.java
public static Set<String> parseZip(String zipFile) { Set<String> data = new HashSet<>(); LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), PhraseExtractor.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override/* w w w . j av a 2s . c o 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); data.addAll(parseFile(temp.toFile().getAbsolutePath())); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } return data; }
From source file:net.minecrell.quartz.launch.mappings.MappingsLoader.java
public static Mappings load(Logger logger) throws IOException { URI source;/* ww w . jav a 2 s. c om*/ try { source = requireNonNull(Mapping.class.getProtectionDomain().getCodeSource(), "Unable to find class source").getLocation().toURI(); } catch (URISyntaxException e) { throw new IOException("Failed to find class source", e); } Path location = Paths.get(source); logger.debug("Mappings location: {}", location); List<ClassNode> mappingClasses = new ArrayList<>(); // Load the classes from the source if (Files.isDirectory(location)) { // We're probably in development environment or something similar // Search for the class files Files.walkFileTree(location.resolve(PACKAGE), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".class")) { try (InputStream in = Files.newInputStream(file)) { ClassNode classNode = MappingsParser.loadClassStructure(in); mappingClasses.add(classNode); } } return FileVisitResult.CONTINUE; } }); } else { // Go through the JAR file try (ZipFile zip = new ZipFile(location.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = StringUtils.removeStart(entry.getName(), MAPPINGS_DIR); if (entry.isDirectory() || !name.endsWith(".class") || !name.startsWith(PACKAGE_PREFIX)) { continue; } // Ok, we found something try (InputStream in = zip.getInputStream(entry)) { ClassNode classNode = MappingsParser.loadClassStructure(in); mappingClasses.add(classNode); } } } } return new Mappings(mappingClasses); }
From source file:org.apdplat.superword.extract.DefinitionExtractor.java
public static Set<Word> parseZip(String zipFile) { Set<Word> data = new HashSet<>(); 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// w ww. j ava 2 s .c o 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); data.addAll(parseFile(temp.toFile().getAbsolutePath())); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } return data; }
From source file:com.ilscipio.scipio.common.FileListener.java
/** * Start a file listener (WatchService) and run a service of a given name and writes the result to the database * Can be used to implements EECAs to auto-update information based on file changes **///from w w w . ja v a 2s . c o m public static void startFileListener(String name, String location) { try { if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(location)) { if (getThreadByName(name) != null) { Debug.logInfo("Filelistener " + name + " already started. Skipping...", module); } else { URL resLocation = UtilURL.fromResource(location); Path folderLocation = Paths.get(resLocation.toURI()); if (folderLocation == null) { throw new UnsupportedOperationException("Directory not found"); } final WatchService folderWatcher = folderLocation.getFileSystem().newWatchService(); // register all subfolders Files.walkFileTree(folderLocation, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { dir.register(folderWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); return FileVisitResult.CONTINUE; } }); // start the file watcher thread below ScipioWatchQueueReader fileListener = new ScipioWatchQueueReader(folderWatcher, name, location); ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor( FILE_LISTENER_THREAD_GROUP, "filelistener-startup", Runtime.getRuntime().availableProcessors(), 0, true); try { executor.submit(fileListener, name); } finally { executor.shutdown(); } Debug.logInfo("Starting FileListener thread for " + name, module); } } } catch (Exception e) { Debug.logError("Could not start FileListener " + name + " for " + location + "\n" + e, module); } }
From source file:de.tudarmstadt.ukp.dkpro.discourse.pdtbparser.PDTBParserWrapper.java
public PDTBParserWrapper() throws IOException { tempDirectory = Files.createTempDirectory("temp_pdtb"); // FileUtils.copyFileToDirectory(); File tempDir = tempDirectory.toFile(); File tmpFile = File.createTempFile("tmp_pdtb", ".zip"); InputStream stream = getClass().getClassLoader().getResourceAsStream("pdtb-parser-v120415.zip"); FileUtils.copyInputStreamToFile(stream, tmpFile); ZipFile zipFile;/*from ww w . j av a 2 s .co m*/ try { zipFile = new ZipFile(tmpFile); zipFile.extractAll(tempDir.getAbsolutePath()); } catch (ZipException e) { throw new IOException(e); } // delete temp file FileUtils.forceDelete(tmpFile); String folderPrefix = "/pdtb-parser-v120415/src"; String srcDir = tempDir.getCanonicalPath() + folderPrefix; // copy rewritten rb files copyFiles(new File(srcDir), "article.rb", "parser.rb"); Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Set<PosixFilePermission> permissions = new HashSet<>(); permissions.add(PosixFilePermission.OWNER_EXECUTE); permissions.add(PosixFilePermission.GROUP_EXECUTE); permissions.add(PosixFilePermission.OTHERS_EXECUTE); permissions.add(PosixFilePermission.OWNER_READ); permissions.add(PosixFilePermission.GROUP_READ); permissions.add(PosixFilePermission.OTHERS_READ); Files.setPosixFilePermissions(file, permissions); return super.visitFile(file, attrs); } }); parserRubyScript = srcDir + "/parser.rb"; System.out.println(parserRubyScript); }
From source file:org.sonarsource.commandlinezip.ZipUtils7.java
public static void smartReportZip(final Path srcDir, Path zip) throws IOException { try (final OutputStream out = FileUtils.openOutputStream(zip.toFile()); final ZipOutputStream zout = new ZipOutputStream(out)) { Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() { @Override/* w w w . ja v a2 s .c om*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) { String entryName = srcDir.relativize(file).toString(); int level = file.toString().endsWith(".pb") ? ZipOutputStream.STORED : Deflater.DEFAULT_COMPRESSION; zout.setLevel(level); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); IOUtils.copy(in, zout); zout.closeEntry(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.equals(srcDir)) { return FileVisitResult.CONTINUE; } String entryName = srcDir.relativize(dir).toString(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); zout.closeEntry(); return FileVisitResult.CONTINUE; } }); } }
From source file:org.apdplat.superword.extract.SynonymAntonymExtractor.java
public static Set<SynonymAntonym> parseZip(String zipFile) { Set<SynonymAntonym> data = new HashSet<>(); 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 . j a v a 2s .c om 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); data.addAll(parseFile(temp.toFile().getAbsolutePath())); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } return data; }
From source file:ru.histone.staticrender.StaticRenderTest.java
private void assertFilesEqualsInDirs(final Path expectedDir, final Path actualDir) throws IOException { final Set<String> notFoundInResult = new TreeSet(); final Set<String> unexpectedFilesInResult = new TreeSet(); final Set<String> notIdenticalFiles = new TreeSet(); FileVisitor<Path> filesVisitor1 = new SimpleFileVisitor<Path>() { @Override//from w ww . j a v a 2s. c o m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relativePath = expectedDir.relativize(file); String expected = new String(Files.readAllBytes(expectedDir.resolve(relativePath)), "UTF-8"); String actual = null; final Path actualFile = actualDir.resolve(relativePath); if (actualFile.toFile().exists()) { actual = new String(Files.readAllBytes(actualFile), "UTF-8"); if (!expected.equals(actual)) { notIdenticalFiles.add(relativePath.toString()); } } else { notFoundInResult.add(relativePath.toString()); } return FileVisitResult.CONTINUE; } }; FileVisitor<Path> filesVisitor2 = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relativePath = actualDir.relativize(file); String expected = new String(Files.readAllBytes(actualDir.resolve(relativePath)), "UTF-8"); String actual = null; final Path actualFile = expectedDir.resolve(relativePath); if (actualFile.toFile().exists()) { actual = new String(Files.readAllBytes(actualFile), "UTF-8"); if (!expected.equals(actual)) { notIdenticalFiles.add(relativePath.toString()); } } else { unexpectedFilesInResult.add(relativePath.toString()); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(expectedDir, filesVisitor1); Files.walkFileTree(actualDir, filesVisitor2); StringBuilder err = new StringBuilder(); if (notFoundInResult.size() > 0) { err.append("Files not found in result: " + Joiner.on(", ").join(notFoundInResult)).append("\n"); } if (unexpectedFilesInResult.size() > 0) { err.append("Unexpected files found in result: " + Joiner.on(", ").join(unexpectedFilesInResult)) .append("\n"); } if (notIdenticalFiles.size() > 0) { err.append("Files differ in expected and in result: " + Joiner.on(", ").join(notIdenticalFiles)) .append("\n"); } if (err.length() > 0) { fail("Folders diff fail:\n" + err.toString()); } }
From source file:de.ks.file.FileStoreTest.java
@Before public void setUp() throws Exception { controller.startOrResume(new ActivityHint(AddThoughtActivity.class)); cleanup.cleanup();/* w ww. j a v a 2s. c om*/ fileStoreDir = TMPDIR + File.separator + "idnadrevTestStore"; Options.store(fileStoreDir, FileOptions.class).getFileStoreDir(); File file = new File(fileStoreDir); if (file.exists()) { Files.walkFileTree(file.toPath(), 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; } }); } }
From source file:org.openehr.adl.TestingArchetypeProvider.java
private Map<String, String> buildArchetypeIdToClasspathMap(final String classpath) throws IOException { final Map<String, String> result = new HashMap<>(); String baseFile = getClass().getClassLoader().getResource(classpath).getFile(); if (baseFile.contains(":") && baseFile.startsWith("/")) baseFile = baseFile.substring(1); final Path basePath = Paths.get(baseFile); Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() { @Override//from w w w . ja v a 2s . c om public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String filename = file.getFileName().toString(); String ext = FilenameUtils.getExtension(filename); if (ext.equalsIgnoreCase("adls") || ext.equalsIgnoreCase("adl")) { String archetypeId = FilenameUtils.getBaseName(filename); String relativePath = basePath.relativize(file).toString(); result.put(archetypeId, Paths.get(classpath).resolve(relativePath).toString()); } return super.visitFile(file, attrs); } }); return result; }