本文整理汇总了Java中java.nio.file.FileVisitor类的典型用法代码示例。如果您正苦于以下问题:Java FileVisitor类的具体用法?Java FileVisitor怎么用?Java FileVisitor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
FileVisitor类属于java.nio.file包,在下文中一共展示了FileVisitor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testTrackingList
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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")));
}
示例2: testTrackingListWithGlobEdgeCases
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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));
}
示例3: testWindows
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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());
}
示例4: getFileResults
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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;
}
示例5: determinePaths
import java.nio.file.FileVisitor; //导入依赖的package包/类
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;
}
示例6: testParseWorkingExamples
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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);
}
示例7: testParseFailingExamples
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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);
}
示例8: testVisitTypeErrorExamples
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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);
}
示例9: getMatchingFiles
import java.nio.file.FileVisitor; //导入依赖的package包/类
/**
* 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;
}
示例10: listJavaScript
import java.nio.file.FileVisitor; //导入依赖的package包/类
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;
}
示例11: includeDirectory
import java.nio.file.FileVisitor; //导入依赖的package包/类
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);
}
示例12: registerTreeRecursive
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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);
});
}
示例13: testWalkRelativeFileTreeWhenPathIsAFile
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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")));
}
示例14: createClone
import java.nio.file.FileVisitor; //导入依赖的package包/类
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 /
}
示例15: execute
import java.nio.file.FileVisitor; //导入依赖的package包/类
@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
}