Java 类java.nio.file.FileVisitor 实例源码

项目:Re-Collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingList() throws Exception {
    final Path path = fileSystem.getPath("/var/log/syslog");

    Files.createDirectories(path.getParent());
    Files.createFile(path);

    final PathSet pathSet = new GlobPathSet("/var/log", "syslog", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(path, attributes);
        }
    }, fileSystem);
    final Set<Path> paths = pathSet.getPaths();

    assertEquals(path.getParent(), pathSet.getRootPath());
    assertEquals(1, paths.size());
    assertTrue(paths.contains(fileSystem.getPath("/var/log/syslog")));
}
项目:Re-Collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingListWithGlobEdgeCases() throws Exception {
    final String file1 = "/var/log/ups?art/graylog-collector.log";
    final Path path = fileSystem.getPath(file1);

    Files.createDirectories(path.getParent());

    final PathSet pathSet = new GlobPathSet("/var/log/ups?art", "*.{log,gz}", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(path, attributes);
        }
    }, fileSystem);

    final Set<Path> paths = pathSet.getPaths();

    assertEquals(path.getParent(), pathSet.getRootPath());
    assertEquals(1, paths.size());
    assertTrue(paths.contains(path));
}
项目:Re-Collector    文件:GlobPathSetTest.java   
@Test
public void testWindows() throws Exception {
    final FileSystem winFs = newWindowsFileSystem();

    Files.createDirectories(winFs.getPath("C:\\test"));

    final PathSet pathSet = new GlobPathSet("C:\\test", "*.log", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            Files.walkFileTree(basePath, visitor);
        }
    }, winFs);

    assertEquals(winFs.getPath("C:\\test"), pathSet.getRootPath());
    assertTrue(pathSet.getPaths().isEmpty());

    Files.createFile(winFs.getPath("C:\\test\\test.log"));

    assertEquals(ImmutableSet.of(winFs.getPath("C:\\test\\test.log")), pathSet.getPaths());
}
项目:maven-enforcer-char-set-encoding    文件:CharacterSetEncodingRule.java   
@Nonnull
private Collection<FileResult> getFileResults(final Log log, final Path dir) {
    Collection<FileResult> allFiles = new ArrayList<>();
    FileVisitor<Path> fileVisitor = new GetEncodingsFileVisitor(
            log,
            this.getIncludeRegex() != null ? this.getIncludeRegex() : INCLUDE_REGEX_DEFAULT,
            this.getExcludeRegex() != null ? this.getExcludeRegex() : EXCLUDE_REGEX_DEFAULT,
            allFiles
    );
    try {
        Set<FileVisitOption> visitOptions = new LinkedHashSet<>();
        visitOptions.add(FileVisitOption.FOLLOW_LINKS);
        Files.walkFileTree(dir,
                visitOptions,
                Integer.MAX_VALUE,
                fileVisitor
        );
    } catch (Exception e) {
        log.error(e.getCause() + e.getMessage());
    }
    return allFiles;
}
项目:collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingList() throws Exception {
    final Path path = fileSystem.getPath("/var/log/syslog");

    Files.createDirectories(path.getParent());
    Files.createFile(path);

    final PathSet pathSet = new GlobPathSet("/var/log", "syslog", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(path, attributes);
        }
    }, fileSystem);
    final Set<Path> paths = pathSet.getPaths();

    assertEquals(path.getParent(), pathSet.getRootPath());
    assertEquals(1, paths.size());
    assertTrue(paths.contains(fileSystem.getPath("/var/log/syslog")));
}
项目:collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingListWithGlobEdgeCases() throws Exception {
    final String file1 = "/var/log/ups?art/graylog-collector.log";
    final Path path = fileSystem.getPath(file1);

    Files.createDirectories(path.getParent());

    final PathSet pathSet = new GlobPathSet("/var/log/ups?art", "*.{log,gz}", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(path, attributes);
        }
    }, fileSystem);

    final Set<Path> paths = pathSet.getPaths();

    assertEquals(path.getParent(), pathSet.getRootPath());
    assertEquals(1, paths.size());
    assertTrue(paths.contains(path));
}
项目:collector    文件:GlobPathSetTest.java   
@Test
public void testWindows() throws Exception {
    final FileSystem winFs = newWindowsFileSystem();

    Files.createDirectories(winFs.getPath("C:\\test"));

    final PathSet pathSet = new GlobPathSet("C:\\test", "*.log", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            Files.walkFileTree(basePath, visitor);
        }
    }, winFs);

    assertEquals(winFs.getPath("C:\\test"), pathSet.getRootPath());
    assertTrue(pathSet.getPaths().isEmpty());

    Files.createFile(winFs.getPath("C:\\test\\test.log"));

    assertEquals(ImmutableSet.of(winFs.getPath("C:\\test\\test.log")), pathSet.getPaths());
}
项目:wildfly-swarm-fraction-plugin    文件:ModuleGenerator.java   
private Set<String> determinePaths(Predicate<String> pred) throws IOException {
    Path dir = Paths.get(this.project.getBuild().getOutputDirectory());

    Set<String> paths = new HashSet<>();

    if (Files.exists(dir)) {
        FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    if (pred.test(file.toString())) {
                        paths.add(javaSlashize(dir.relativize(file.getParent())));
                    }
                }
                return super.visitFile(file, attrs);
            }
        };

        Files.walkFileTree(dir, visitor);
    }
    return paths;

}
项目:MiniJCompiler    文件:MiniJParserTest.java   
@Test
public void testParseWorkingExamples() throws IOException {
    FileVisitor<Path> workingFilesVisitior = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("Testing parser input from file \""+file.toString()+"\"");
            ANTLRFileStream antlrStream = new ANTLRFileStream(file.toString());
            MiniJLexer lexer = new MiniJLexer(antlrStream);
            TokenStream tokens = new CommonTokenStream(lexer);
            MiniJParser parser = new MiniJParser(tokens);
            parser.setErrorHandler(new BailErrorStrategy());
            parser.prog();
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(EXAMPLE_PROGRAM_PATH_WORKING, workingFilesVisitior);
}
项目:MiniJCompiler    文件:MiniJParserTest.java   
@Test
public void testParseFailingExamples() throws IOException {
    FileVisitor<Path> workingFilesVisitior = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("Testing parser input from file \""+file.toString()+"\"");
            ANTLRFileStream antlrStream = new ANTLRFileStream(file.toString());
            MiniJLexer lexer = new MiniJLexer(antlrStream);
            TokenStream tokens = new CommonTokenStream(lexer);
            MiniJParser parser = new MiniJParser(tokens);
            parser.setErrorHandler(new BailErrorStrategy());
            /*
             * Catch all exceptions first, to ensure that every single
             * compilation unit exits with an Exception. Otherwise, this
             * method will return after the first piece of code.
             */
            try {
                parser.prog();
                fail("The example "+file.toString()+" should have failed, but was accepted by the parser.");
            } catch (ParseCancellationException e) {
            }
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(EXAMPLE_PROGRAM_PATH_FAILING, workingFilesVisitior);
}
项目:MiniJCompiler    文件:TypeCheckVisitorTest.java   
@Test
public void testVisitTypeErrorExamples() throws Exception {
    FileVisitor<Path> failingFilesVisitior = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("LinkedListBUG.java")) {
                return super.visitFile(file, attrs);
            }
            System.out.println("Testing type checker with file \""+file.toString()+"\"");
            ANTLRFileStream reader = new ANTLRFileStream(file.toString());
            MiniJLexer lexer = new MiniJLexer((CharStream) reader);
            TokenStream tokens = new CommonTokenStream(lexer);
            MiniJParser parser = new MiniJParser(tokens);
            ParseTree parseTree = parser.prog();
            ASTVisitor astVisitor = new ASTVisitor();
            Program ast = (Program) astVisitor.visit(parseTree);
            TypeInferenceVisitor typeInferenceVisitor = new TypeInferenceVisitor();
            ast.accept(typeInferenceVisitor);
            TypeCheckVisitor visitor = new TypeCheckVisitor();
            boolean typesCorrect = ast.accept(visitor);
            assertFalse("\"" + file.toString() + "\" passed type check but it shouldn't", typesCorrect);
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(EXAMPLE_PROGRAM_PATH_FAILING, failingFilesVisitior);
}
项目:less-compiler    文件:LessUtils.java   
/**
 * Returns a list of all files matching the given pattern. If {@code recursive} is true
 * will recurse into all directories below {@code rootPath}.
 */
public static List<Path> getMatchingFiles(final Path rootPath, String globPattern, boolean recursive)
    throws IOException {
  final List<Path> result = new ArrayList<>();
  if (!recursive) {
    DirectoryStream<Path> dirStream = getMatchingFiles(rootPath, globPattern);
    for (Path path : dirStream) {
      result.add(path);
    }

  } else {
    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globPattern);
    FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) {
        if (matcher.matches(file.getFileName())) {
          result.add(rootPath.relativize(file));
        }
        return FileVisitResult.CONTINUE;
      }
    };
    Files.walkFileTree(rootPath, visitor);
  }
  return result;
}
项目:qir    文件:JavascriptUnitTestPairTest.java   
private List<String> listJavaScript(String base, String ext)
        throws IOException {
    final List<String> list = new ArrayList<String>();
    FileSystem fs = FileSystems.getDefault();
    PathMatcher matcher = fs.getPathMatcher("glob:" + ext);
    FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attribs) {
            Path name = file.getFileName();
            if (matcher.matches(name)) {
                list.add(file.toString());
            }
            return FileVisitResult.CONTINUE;
        }
    };
    Files.walkFileTree(Paths.get(base), matcherVisitor);
    return list;
}
项目:onos    文件:OSGiWrapper.java   
private void includeDirectory(Jar jar, String destinationRoot, Path sourceRoot)
        throws IOException {
    // iterate through sources
    // put each source on the jar
    FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = sourceRoot.relativize(file);
            String destination = destinationRoot != null ?
                    destinationRoot + "/" + relativePath.toString() : //TODO
                    relativePath.toString();

            addFileToJar(jar, destination, file.toAbsolutePath().toString());
            return FileVisitResult.CONTINUE;
        }
    };

    walkFileTree(sourceRoot, visitor);
}
项目:jooby    文件:FileMonitorTest.java   
@SuppressWarnings("unchecked")
@Test
public void registerTreeRecursive() throws Exception {
  new MockUnit(Injector.class, Env.class, WatchService.class, FileEventOptions.class, Path.class,
      WatchEvent.Kind.class, WatchEvent.Modifier.class, WatchKey.class)
      .expect(newThread)
      .expect(registerTree(true, false))
      .expect(takeInterrupt)
      .run(unit -> {
        FileMonitor monitor = new FileMonitor(unit.get(Injector.class), unit.get(Env.class),
            unit.get(WatchService.class),
            ImmutableSet.of(unit.get(FileEventOptions.class)));
        unit.captured(ThreadFactory.class).get(0).newThread(monitor);
      }, unit -> {
        unit.captured(Runnable.class).get(0).run();
        unit.captured(FileVisitor.class).get(0).preVisitDirectory(unit.get(Path.class), null);
      });
}
项目:buck    文件:FakeProjectFilesystemTest.java   
@Test
public void testWalkRelativeFileTreeWhenPathIsAFile() throws IOException {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  filesystem.touch(Paths.get("A.txt"));

  final List<Path> filesVisited = new ArrayList<>();

  FileVisitor<Path> fileVisitor =
      new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
          filesVisited.add(path);
          return FileVisitResult.CONTINUE;
        }
      };

  filesystem.walkRelativeFileTree(Paths.get("A.txt"), fileVisitor);

  // Despite the awkward name, "contains" implies an exact match.
  assertThat(filesVisited, contains(Paths.get("A.txt")));
}
项目:linulator    文件:CloneFilesystem.java   
public static void createClone() throws IOException
{
  Scanner scanner = new Scanner(System.in);
  String input = null;

  System.out.println("\n!!! This program _may_ not function as intended. Please report any hangs or bugs to the developers. !!!");
  System.out.println("Known issues:");
  System.out.println("1. Link counts are not currently supported. A default of '1' link (file itself) is recorded.");
  System.out.println("2. Setuid, setgid, and sticky bits are not currently supported.\n");
  System.out.println("Warning: This should only be performed on a fresh install to avoid importing personal data!");
  System.out.print("Type \"yes\" and press enter if you understand this and want to proceed: ");
  input = scanner.nextLine();

  if(!input.equalsIgnoreCase("yes"))
  {
    System.out.println("Process aborted per user request.");
    shutdownDatabase();
    System.exit(0);
  }

  FileVisitor<Path> fileProcessor = new ProcessFile();
  Files.walkFileTree(Paths.get("/"), fileProcessor);   // get everything under /
}
项目:logging-log4j2    文件:DeleteAction.java   
@Override
public boolean execute(final FileVisitor<Path> visitor) throws IOException {
    final List<PathWithAttributes> sortedPaths = getSortedPaths();
    trace("Sorted paths:", sortedPaths);

    for (final PathWithAttributes element : sortedPaths) {
        try {
            visitor.visitFile(element.getPath(), element.getAttributes());
        } catch (final IOException ioex) {
            LOGGER.error("Error in post-rollover Delete when visiting {}", element.getPath(), ioex);
            visitor.visitFileFailed(element.getPath(), ioex);
        }
    }
    // TODO return (visitor.success || ignoreProcessingFailure)
    return true; // do not abort rollover even if processing failed
}
项目:logging-log4j2    文件:PosixViewAttributeAction.java   
@Override
protected FileVisitor<Path> createFileVisitor(final Path basePath,
        final List<PathCondition> conditions) {
    return new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            for (final PathCondition pathFilter : conditions) {
                final Path relative = basePath.relativize(file);
                if (!pathFilter.accept(basePath, relative, attrs)) {
                    LOGGER.trace("Not defining posix attribute base={}, relative={}", basePath, relative);
                    return FileVisitResult.CONTINUE;
                }
            }
            FileUtils.defineFilePosixAttributeView(file, filePermissions, fileOwner, fileGroup);
            return FileVisitResult.CONTINUE;
        }
    };
}
项目:n4js    文件:UpdateShippedCode.java   
private static void cleanJsonFiles(File workingDirectory) {
    println("Cleaning of Json file started...");
    FileVisitor<Path> fileVisitor = new PackageJsonVisitor();
    try {
        Files.walkFileTree(workingDirectory.toPath().resolve(ExternalLibrariesActivator.NPM_CATEGORY),
                fileVisitor);
    } catch (Exception e) {
        e.printStackTrace();
    }
    println("Cleaning of Json file finished.");
}
项目:Re-Collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingListWithGlob() throws Exception {
    final String file1 = "/var/log/upstart/graylog-collector.log";
    final String file2 = "/var/log/test/compressed.log.1.gz";
    final String file3 = "/var/log/foo/bar/baz/test.log";
    final String file4 = "/var/log/test.log";

    Files.createDirectories(fileSystem.getPath(file1).getParent());
    Files.createDirectories(fileSystem.getPath(file2).getParent());
    Files.createDirectories(fileSystem.getPath(file3).getParent());
    Files.createDirectories(fileSystem.getPath(file4).getParent());

    final PathSet list = new GlobPathSet("/var/log", "**/*.{log,gz}", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(fileSystem.getPath(file1), attributes);
            visitor.visitFile(fileSystem.getPath(file2), attributes);
            visitor.visitFile(fileSystem.getPath(file3), attributes);
            visitor.visitFile(fileSystem.getPath(file4), attributes);
        }
    }, fileSystem);

    final Set<Path> paths = list.getPaths();

    assertEquals(fileSystem.getPath("/var/log"), list.getRootPath());
    assertEquals(3, paths.size());
    assertTrue(paths.contains(fileSystem.getPath(file1)));
    assertTrue(paths.contains(fileSystem.getPath(file2)));
    assertTrue(paths.contains(fileSystem.getPath(file3)));
    assertFalse(paths.contains(fileSystem.getPath(file4)));
}
项目:neoscada    文件:Application.java   
private static void deleteRecursive ( final File updates ) throws IOException
{
    System.out.println ( "Deleting: " + updates );

    final FileVisitor<? super Path> visitor = new RecursiveDeleteVisitior ();

    Files.walkFileTree ( updates.toPath (), visitor );
}
项目:source-graph-viewer    文件:Viewer.java   
private static List<File> getFilesRecursively(final String[] extensions) {
  List<File> files = new ArrayList<>();

  FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
      for (String extension : extensions) {
        if (filePath.toString().endsWith("." + extension)) {
          files.add(filePath.toFile());
          break;
        }
      }
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
      return FileVisitResult.CONTINUE;
    }
  };

  try {
    Files.walkFileTree(Paths.get("target/test-jars"), visitor);
  } catch (IOException e) {
    // we already ignore errors in the visitor
  }

  return files;
}
项目:athena    文件:OSGiWrapper.java   
private void includeFiles(Jar jar, String destinationRoot, String sourceRoot)
        throws IOException {
    Path sourceRootPath = Paths.get(sourceRoot);
    // iterate through sources
    // put each source on the jar
    FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = sourceRootPath.relativize(file);
            String destination = destinationRoot != null ?
                    destinationRoot + "/" + relativePath.toString() : //TODO
                    relativePath.toString();

            addFileToJar(jar, destination, file.toAbsolutePath().toString());
            return FileVisitResult.CONTINUE;
        }
    };
    File dir = new File(sourceRoot);
    if (dir.isFile()) {
        addFileToJar(jar, destinationRoot, dir.getAbsolutePath());
    } else if (dir.isDirectory()) {
        walkFileTree(sourceRootPath, visitor);
    } else {
        warn("Skipping resource in bundle %s: %s (File Not Found)\n",
             bundleSymbolicName, sourceRoot);
    }
}
项目:personium-core    文件:SnapshotFileExportRunner.java   
/**
 * Extract data from WebDAV and add it to the zip file.
 * Encrypted data is decrypted.
 * @param snapshotFile snapshot file
 */
private void addWebDAVToZip(SnapshotFile snapshotFile) {
    Path webdavRootPathInZip = snapshotFile.getWebDAVDirPath();
    Path webdavRootPath = Paths.get(PersoniumUnitConfig.getBlobStoreRoot(),
            targetCell.getDataBundleName(), targetCell.getId());
    // Use FileVisitor to process files recursively
    FileVisitor<Path> visitor = new SnapshotFileExportVisitor(targetCell.getId(),
            webdavRootPath, webdavRootPathInZip, progressInfo);
    try {
        Files.walkFileTree(webdavRootPath, visitor);
    } catch (IOException e) {
        throw PersoniumCoreException.Common.FILE_IO_ERROR.params("add webdav data to snapshot file").reason(e);
    }
}
项目:personium-core    文件:SnapshotFileImportRunner.java   
/**
 * Extract webdav file from snapshot file and add it to cell.
 * Encrypt the file according to the setting of the unitconfig property.
 * @param snapshotFile snapshot file
 */
private void addWebDAVToCell(SnapshotFile snapshotFile) {
    Path webdavRootPathInZip = snapshotFile.getWebDAVDirPath();
    Path webdavRootPath = Paths.get(PersoniumUnitConfig.getBlobStoreRoot(),
            targetCell.getDataBundleName(), targetCell.getId());
    // Use FileVisitor to process files recursively
    FileVisitor<Path> visitor = new SnapshotFileImportVisitor(targetCell.getId(),
            webdavRootPath, webdavRootPathInZip.toAbsolutePath(), progressInfo);
    try {
        Files.walkFileTree(webdavRootPathInZip.toAbsolutePath(), visitor);
    } catch (IOException e) {
        throw PersoniumCoreException.Common.FILE_IO_ERROR.params("copy webdav data from snapshot file").reason(e);
    }
}
项目:collector    文件:GlobPathSet.java   
public GlobPathSet(final String rootPathString, final String pattern) {
    this(rootPathString, pattern, new FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            Files.walkFileTree(basePath, visitor);
        }
    });
}
项目:collector    文件:GlobPathSetTest.java   
@Test
public void testTrackingListWithGlob() throws Exception {
    final String file1 = "/var/log/upstart/graylog-collector.log";
    final String file2 = "/var/log/test/compressed.log.1.gz";
    final String file3 = "/var/log/foo/bar/baz/test.log";
    final String file4 = "/var/log/test.log";

    Files.createDirectories(fileSystem.getPath(file1).getParent());
    Files.createDirectories(fileSystem.getPath(file2).getParent());
    Files.createDirectories(fileSystem.getPath(file3).getParent());
    Files.createDirectories(fileSystem.getPath(file4).getParent());

    final PathSet list = new GlobPathSet("/var/log", "**/*.{log,gz}", new GlobPathSet.FileTreeWalker() {
        @Override
        public void walk(Path basePath, FileVisitor<Path> visitor) throws IOException {
            visitor.visitFile(fileSystem.getPath(file1), attributes);
            visitor.visitFile(fileSystem.getPath(file2), attributes);
            visitor.visitFile(fileSystem.getPath(file3), attributes);
            visitor.visitFile(fileSystem.getPath(file4), attributes);
        }
    }, fileSystem);

    final Set<Path> paths = list.getPaths();

    assertEquals(fileSystem.getPath("/var/log"), list.getRootPath());
    assertEquals(3, paths.size());
    assertTrue(paths.contains(fileSystem.getPath(file1)));
    assertTrue(paths.contains(fileSystem.getPath(file2)));
    assertTrue(paths.contains(fileSystem.getPath(file3)));
    assertFalse(paths.contains(fileSystem.getPath(file4)));
}
项目:MiniJCompiler    文件:MiniJParserTest.java   
@Test
public void testTypeFailingExamples() throws IOException {
    FileVisitor<Path> typeFailingFilesVisitior = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("Testing type for file \""+file.toString()+"\"");
            ANTLRFileStream antlrStream = new ANTLRFileStream(file.toString());
            MiniJLexer lexer = new MiniJLexer(antlrStream);
            TokenStream tokens = new CommonTokenStream(lexer);
            MiniJParser parser = new MiniJParser(tokens);

            ParseTree tree = parser.prog();
            ASTVisitor astVisitor = new ASTVisitor();
            Program program = (Program) astVisitor.visit(tree);
            TypeInferenceVisitor typeInferenceVisitor = new TypeInferenceVisitor();
            program.accept(typeInferenceVisitor);

            TypeCheckVisitor typeCheckVisitor = new TypeCheckVisitor();
            if (program.accept(typeCheckVisitor)) {
                fail("The example "+file.toString()+" should have failed, but was accepted by the type checker.");
            }

            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(EXAMPLE_PROGRAM_PATH_TYPE_FAILING, typeFailingFilesVisitior);
}
项目:MiniJCompiler    文件:TypeCheckVisitorTest.java   
@Test
public void testVisitWorkingExamples() throws Exception {
    FileVisitor<Path> workingFilesVisitior = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("Testing type checker with file \""+file.toString()+"\"");
            ANTLRFileStream reader = new ANTLRFileStream(file.toString());
            MiniJLexer lexer = new MiniJLexer((CharStream) reader);
            TokenStream tokens = new CommonTokenStream(lexer);
            MiniJParser parser = new MiniJParser(tokens);
            ParseTree parseTree = parser.prog();
            ASTVisitor astVisitor = new ASTVisitor();
            Program ast = (Program) astVisitor.visit(parseTree);
            TypeInferenceVisitor typeInferenceVisitor = new TypeInferenceVisitor();
            ast.accept(typeInferenceVisitor);
            TypeCheckVisitor visitor = new TypeCheckVisitor();
            boolean typesCorrect = ast.accept(visitor);
            if (!typesCorrect) {
                for (String error : visitor.getErrors()) {
                    System.err.println(error);
                }
            }
            assertTrue(typesCorrect);
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(EXAMPLE_PROGRAM_PATH_WORKING, workingFilesVisitior);
}
项目:java7examples    文件:IOandNewIO.java   
static void fileVisitor(Path path) throws IOException {
    FileVisitor<? super Path> visitor = new MySimpleFileVisitor();
    try {
        Files.walkFileTree(path, visitor);
    } catch (IOException e) {
        System.out.println("Failed to walk: " + e.getMessage());
    }
    visitor = new MyNotSoSimpleFileVisitor();
    Files.walkFileTree(path, visitor);
}
项目:ph-commons    文件:PathHelper.java   
@Nonnull
public static Path walkFileTree (@Nonnull final Path aStart,
                                 @Nonnegative final int nMaxDepth,
                                 @Nonnull final FileVisitor <? super Path> aVisitor)
{
  return walkFileTree (aStart, EnumSet.noneOf (FileVisitOption.class), nMaxDepth, aVisitor);
}
项目:avaje-website-generator    文件:SiteWatchRender.java   
/**
 * Walks the source directory and processes the files.
 */
public void render() throws IOException {

  log.info("source:{} dest:{}", sourceDirectory, destinationDirectory);
  FileVisitor<Path> fileProcessor = new DirectoryWalkProcessFile();
  Files.walkFileTree(sourceDirectory, fileProcessor);
}
项目:onos    文件:OSGiWrapper.java   
private void includeFiles(Jar jar, String destinationRoot, String sourceRoot)
        throws IOException {
    Path sourceRootPath = Paths.get(sourceRoot);
    // iterate through sources
    // put each source on the jar
    FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = sourceRootPath.relativize(file);
            String destination = destinationRoot != null ?
                    destinationRoot + "/" + relativePath.toString() : //TODO
                    relativePath.toString();

            addFileToJar(jar, destination, file.toAbsolutePath().toString());
            return FileVisitResult.CONTINUE;
        }
    };
    File dir = new File(sourceRoot);
    if (dir.isFile()) {
        addFileToJar(jar, destinationRoot, dir.getAbsolutePath());
    } else if (dir.isDirectory()) {
        walkFileTree(sourceRootPath, visitor);
    } else {
        warn("Skipping resource in bundle %s: %s (File Not Found)\n",
             bundleSymbolicName, sourceRoot);
    }
}
项目:buck-cutom    文件:WorkspaceGenerator.java   
private void walkNodeTree(FileVisitor<Map.Entry<String, WorkspaceNode>> visitor)
    throws IOException{
  Stack<Iterator<Map.Entry<String, WorkspaceNode>>> iterators = new Stack<>();
  Stack<Map.Entry<String, WorkspaceNode>> groups = new Stack<>();
  iterators.push(this.children.entrySet().iterator());
  while (!iterators.isEmpty()) {
    if (!iterators.peek().hasNext()) {
      if (groups.isEmpty()) {
        break;
      }
      visitor.postVisitDirectory(groups.pop(), null);
      iterators.pop();
      continue;
    }
    Map.Entry<String, WorkspaceNode> nextEntry = iterators.peek().next();
    WorkspaceNode nextNode = nextEntry.getValue();
    if (nextNode instanceof WorkspaceGroup) {
      visitor.preVisitDirectory(nextEntry, null);
      WorkspaceGroup nextGroup = (WorkspaceGroup) nextNode;
      groups.push(nextEntry);
      iterators.push(nextGroup.getChildren().entrySet().iterator());
    } else if (nextNode instanceof WorkspaceFileRef) {
      visitor.visitFile(nextEntry, null);
    } else {
      // Unreachable
      throw new HumanReadableException(
          "Expected a workspace to only contain groups and file references");
    }
  }
}
项目:buck-cutom    文件:ProjectFilesystem.java   
/**
 * Similar to {@link #walkFileTree(Path, FileVisitor)} except this takes in a path relative to
 * the project root.
 */
public void walkRelativeFileTree(
    Path pathRelativeToProjectRoot,
    final FileVisitor<Path> fileVisitor) throws IOException {
  walkRelativeFileTree(pathRelativeToProjectRoot,
      EnumSet.of(FileVisitOption.FOLLOW_LINKS),
      fileVisitor);
}
项目:buck-cutom    文件:FakeProjectFilesystemTest.java   
@Test
public void testWalkRelativeFileTree() throws IOException {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  filesystem.touch(Paths.get("root/A.txt"));
  filesystem.touch(Paths.get("root/A/B/C.txt"));
  filesystem.touch(Paths.get("root/A/B.txt"));

  final List<Path> filesVisited = Lists.newArrayList();

  FileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
      filesVisited.add(path);
      return FileVisitResult.CONTINUE;
    }
  };

  filesystem.walkRelativeFileTree(Paths.get("root"), fileVisitor);
  assertThat(filesVisited, containsInAnyOrder(
          Paths.get("root/A.txt"),
          Paths.get("root/A/B/C.txt"),
          Paths.get("root/A/B.txt")));

  filesVisited.clear();
  filesystem.walkRelativeFileTree(Paths.get("root/A"), fileVisitor);
  assertThat(
      filesVisited, containsInAnyOrder(
          Paths.get("root/A/B/C.txt"),
          Paths.get("root/A/B.txt")));
}
项目:buck-cutom    文件:FakeProjectFilesystem.java   
/**
 * TODO(natthu): (1) Also traverse the directories. (2) Do not ignore return value of
 * {@code fileVisitor}.
 */
@Override
public void walkRelativeFileTree(Path path, FileVisitor<Path> fileVisitor) throws IOException {
  Preconditions.checkArgument(!fileContents.containsKey(path),
      "FakeProjectFilesystem only supports walkRelativeFileTree over directories.");
  for (Path file : getFilesUnderDir(path)) {
    fileVisitor.visitFile(file, DEFAULT_FILE_ATTRIBUTES);
  }
}
项目:CLIFF    文件:ReutersFocusChecker.java   
public void check() throws IOException{
    FileVisitor<Path> fileProcessor = new ProcessFile();
    Files.walkFileTree(Paths.get(BASE_DIR), fileProcessor);
    double success = (double)mentionsArticlesWeGotRight/(double)articlesWithLocations; 
    double focusSuccess = (double)focusArticlesWeGotRight/(double)articlesWithLocations; 
    logger.info("Checked "+articlesWithLocations+" Articles - Base success rate: "+success);
    logger.info("Checked "+articlesWithLocations+" Articles - Aboutness success rate: "+focusSuccess);
}
项目:CLIFF    文件:NYTFocusChecker.java   
public void check() throws IOException {
    FileVisitor<Path> fileProcessor = new ProcessFile();
    Files.walkFileTree(Paths.get(NYT_BASE_DIR), fileProcessor);
    double success = (double)articlesWeGotRight/(double)articlesWithLocations; 
    double focusSuccess = (double)focusArticlesWeGotRight/(double)articlesWithLocations; 
    logger.info("Checked "+articlesWithLocations+" Articles - Base success rate: "+success);
    logger.info("Checked "+articlesWithLocations+" Articles - Aboutness success rate: "+focusSuccess);        
}