Java 文件夹名称中的最后一个字符可以是';不可替代

Java 文件夹名称中的最后一个字符可以是';不可替代,java,formatting,directory,rename,Java,Formatting,Directory,Rename,我使用.replace()指令来清除文件夹名称。到目前为止,这对这些字符非常有效:{“,”,“(“,“[”}但是,当我到达结束括号时,我收到一个错误。当我查看抛出此错误的文件夹时,它的末尾总是有一个结束括号。手动删除结束括号并再次执行代码后,下一个带有尾随括号的文件夹会发生错误 在每种情况下,字符都被替换为一个空格 public void cleanFormat() { for (int i = 0; i < directories.size(); i++) { F

我使用.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");
}

出现此异常是因为文件名中的最后一个字符是空格,而基础操作系统(Windows)将不接受尾随空格字符的文件名


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

你说得对。我已经坚持了一天,在发布它的那一刻,我突然想到了“<>”是指单个空格,而我认为它与“”字符。当我发现这一点时,我需要确保名称不以单个空格结尾。我之前尝试过此选项,手动将空格放在文件夹的末尾,因为它没有给出错误,所以我认为可以。我从未想过再次检查名称(我现在这样做了:windows会自动删除空格)。
if(formattedName.endsWith(“”)
formattedName=
formattedName.substring(0,formattedName.length()-1);
这段代码应该放在所有格式化表达式的末尾,然后解决它。}您也可以这样做:
formattedName=formattedName.replaceAll(“\\s+$”,”);
替换ome快照中的所有多个尾随空格。anubhava:非常感谢!@jeroenvanevel它不能处理以两个空格结尾的字符串;)
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]