2015-05-28 16 views
0

我正在使用SimpleFileVisitor來搜索文件。它在Windows和Linux上運行良好。但是,當我嘗試在Unix上使用它時,如操作系統它不能按預期工作。我會得到這樣的錯誤:如何在Java中使用SimpleFileVisitor來查找編碼可能不同的文件名?

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; 
} 
+1

通常,當您看到「?」字符時,表示您有一個正在被解釋爲ISO-8859-1或WIN-1252的UTF-8流。 「â」是來自UTF-8的多字節指示,它是錯誤翻譯的。 –

回答

1

嘗試使用 「Charset.defaultCharset()」 當您創建的 「文件」 和「DIR 「你經過的琴絃。否則,在創建這些字符串以將它們傳遞給您的訪問方法的過程中,您很可能會破壞名稱。

你也可以檢查你正在運行的JVM上的默認編碼,如果它與你正在閱讀的文件系統不同步,你的結果將會是錯誤的,不可預測的。

相關問題