5

フォルダー名をクリーンアップするために .replace() 命令を使用します。これまでのところ、これらの文字に対しては問題なく機能していました: {".", " ", "(", "["} しかし、閉じ括弧に到達するとすぐにエラーが発生します。これをスローしたフォルダーを見ると、 error it always has a closed bracket at the end. 手動で閉じかっこを削除してコードを再度実行すると、末尾にかっこがある次のフォルダーでエラーが発生します。

いずれの場合も、文字は単一のスペースに置き換えられています。

public void cleanFormat() {
    for (int i = 0; i < directories.size(); i++) {
        File currentDirectory = directories.get(i);
        for (File currentFile : currentDirectory.listFiles()) {
            String formattedName = currentFile.getName();
            formattedName = formattedName.replace(".", " ");
            formattedName = formattedName.replace("(", " ");
            formattedName = formattedName.replace(")", " "); // error here
            formattedName = formattedName.replace("[", " ");
            formattedName = formattedName.replace("]", " "); // and here
            formattedName = formattedName.replace("  ", " ");
            Path source = currentFile.toPath();
            try {
                Files.move(source, source.resolveSibling(formattedName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    JOptionPane.showMessageDialog(null, "All folders have been formatted");
}

エラー:

Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Trailing char < > at index 68: A Good Old Fashioned Orgy 2011 LIMITED 720p BluRay X264-AMIABLE EtHD 
at sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at sun.nio.fs.AbstractPath.resolveSibling(Unknown Source)
at domain.DirectoryListing.cleanFormat(DirectoryListing.java:86)

フォルダ名:

A Good Old Fashioned Orgy 2011 LIMITED 720p BluRay X264-AMIABLE EtHD]
4

1 に答える 1

12

ファイル名の最後の文字としてスペースがあり、基盤となる OS (Windows) が末尾にスペース文字のあるファイル名を受け入れないため、この例外が発生します。

末尾の文字としてのこのスペースは、複数の呼び出しの結果である可能性が最も高いためString#replace、文字列の最後の文字をスペースに置き換えないようにしてください。

于 2012-12-08T14:05:45.643 に答える