加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 08:48:27 所属栏目:Java 来源:网络整理
导读:我使用.replace()指令来清理文件夹名称.到目前为止,这对于这些字符工作正常:{“.”,“”,“(”,“[”}但是当我到达右括号时,我收到一个错误.当我看到扔掉这个的文件夹时错误它总是有一个结束括号.手动删除结束括号并再次执行代码时,下一个带有尾随括号的文
我使用.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]

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读