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

Posted

技术标签:

【中文标题】文件夹名称中的最后一个字符无法替换【英文标题】:The last character in a folder name can't be replaced 【发布时间】:2012-11-26 12:27:25 【问题描述】:

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

错误是:

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]

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

你是对的。我在这个问题上卡了一天,在我发布它的那一刻,它突然袭击了我:“”是指一个空格,而我认为它与“”有关特点。当我发现这一点时,问题是确保名称不会以单个空格结尾。我之前通过在文件夹末尾手动放置一个空格来尝试此选项,并且由于它没有给出错误,我认为它很好。我从没想过再次检查名称(我现在做了:windows 会自动删除空间)。 if(formattedName.endsWith(" ")) formattedName = formattedName.substring(0,formattedName.length()-1); 这段代码应该放在所有格式化表达式的最后,就解决了。 您也可以这样做:formattedName=formattedName.replaceAll("\\s+$", ""); 替换 ome shot 中的所有多个尾随空格。 anubhava:非常感谢! @JeroenVannevel 它不适用于以两个空格结尾的字符串;)

以上是关于文件夹名称中的最后一个字符无法替换的主要内容,如果未能解决你的问题,请参考以下文章

java中替换String中的最后一个字符

使用 linux 和 AIX 的正则表达式替换 bash 脚本中的字符串

无法匹配和替换文本文件中的 " 和 ' 字符

如何根据php文件中的名称替换.txt文件中的字符串?

使用 GSUTIL 替换字符串

无法删除 Pig 中的特殊字符