我SimpleFileVisitor
用来搜索文件。它在 Windows 和 Linux 上运行良好。但是,当我尝试在 Unix 之类的操作系统上使用它时,它并没有按预期工作。我会收到这样的错误:
java.nio.file.NoSuchFileException:
/File/Location/MyFolder/\u0082\u0096\u0096âĜu0099\u0081\u0097K
\u0097\u0099\u0096\u0097\u0085\u0099Ĝu0089\u0085
看起来获得的名称采用不同的字符编码,这可能是导致问题的原因。看起来在获取名称和尝试获取对文件的访问权之间,编码被遗漏了。这导致它尝试访问的每个文件都调用preVisitDirectory
一次。visitFileFailed
我不确定为什么该walkFileTree
方法会这样做。任何想法?
我的SimpleFileVisitor
代码使用如下所示:
Files.walkFileTree(serverLocation, finder);
我的SimpleFileVisitor
班级:
public class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private final List<Path> matchedPaths = new ArrayList<Path>();
private String usedPattern = null;
Finder(String pattern) {
this.usedPattern = pattern;
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void match(Path file) { //Compare pattern against file or dir
Path name = file.getFileName();
if (name != null && matcher.matches(name))
matchedPaths.add(file);
}
// Check each file.
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
match(file);
return CONTINUE;
}
// Check each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
match(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.println("Issue: " + e );
return CONTINUE;
}