无法替换文件夹名称中的最后一个字符

Jer*_*vel 3 java directory formatting rename

我使用.replace()指令来清理文件夹名称.到目前为止,这对于这些字符工作得很好:{".","","(","["}但是当我到达右括号时,我收到一个错误.当我看到扔掉这个的文件夹时错误它总是有一个结束括号.手动删除结束括号并再次执行代码时,下一个带有尾随括号的文件夹发生错误.

在每种情况下,字符都被替换为单个空格.

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");
}
Run Code Online (Sandbox Code Playgroud)

错误是:

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)
Run Code Online (Sandbox Code Playgroud)

文件夹名称:

A Good Old Fashioned Orgy 2011 LIMITED 720p BluRay X264-AMIABLE EtHD]
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 7

您将收到此异常,因为您的文件名中有一个空格作为最后一个字符,而底层操作系统(Windows)将不接受带尾随空格字符的文件名.

此空格作为尾随字符很可能是多次String#replace调用的结果,请确保不要使用空格替换String中的最后一个char.

  • `if(formattedName.endsWith(""))````formattedName =``formattedName.substring(0,formattedName.length() - 1);`这段代码应该放在所有格式化表达式的末尾它解决了.} (2认同)
  • 你也可以:`formattedName = formattedName.replaceAll("\\ s + $","");`替换ome镜头中的所有多个尾随空格. (2认同)