我正在使用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;
}发布于 2015-05-29 05:20:09
在创建传递给您的“文件”和"dir“字符串时,尝试使用"Charset.defaultCharset()”。否则,您很可能会在创建这些字符串的过程中损坏名称,将它们传递给您的访问方法。
您还可以检查您正在运行的JVM上的默认编码,如果它与您正在读取的文件系统不同步,您的结果将是不可预测的。
https://stackoverflow.com/questions/30517700
复制相似问题