删除文件夹中部分文件名 [英] Removing Parts of File names in Folder

查看:185
本文介绍了删除文件夹中部分文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有效,但是我的问题是控制台输出正确显示,例如:

The code below works, but my problem is that the console output shows correctly for example:

3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMAW-22017
3-M-ALABAMAW-22017

上面的输出显示我的索引是-2017,但是当更改文件夹中的实际文件名时,某些文件名将被跳过.例如

The output above show that my index is -2017 however when the actual file name is being change in the folder some of the File Names are skipped. For example

原始文件名:3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140
控制台输出:3-M-ALABAMA-SUIQUARTER2
文件夹中的某些文件未更改:3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140

Orginal file name: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140
Console Output: 3-M-ALABAMA-SUIQUARTER2
Some of Files in folder unchanged: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140

但是,文件夹中的某些文件为3-M-BATTLECREEKMIW-22017-2017200346-CD619B,而某些文件为3-M-ARLINGTONOHLOCALW-2-2017200346-CD61A8

However some of the files in the folder have 3-M-BATTLECREEKMIW-22017-2017200346-CD619B and some are 3-M-ARLINGTONOHLOCALW-2-2017200346-CD61A8

因此,我认为在文件更改中进行实际更改时,java对于在何处中断感到困惑?你能帮助我吗?

So I think java is confused as to where to cut off when the actual change is being made in file alteration? can you help me?

for(File file:filesInDir) {
       x++;
       String name = file.getName().substring(0, file.getName().indexOf("-2017"));
       String newName = name;
       System.out.println(newName); // prints prints to file 
       String newPath = absolutePathOne + "\\" + newName;
       file.renameTo(new File(newPath));
}

推荐答案

还可以使用其他方法重命名文件吗?

是的.使用较新的NIO 2类,尤其是

Yes. Use the newer NIO 2 classes, in particular the Files.move() method.

至少将file.renameTo(new File(newPath))替换为:

Files.move(file.toPath(), Paths.get(newPath));

如果移动失败,将抛出描述性异常,而不是

That will throw descriptive exception if move fails, instead of the false boolean return value from renameTo().

您还应该更改其余代码以使用较新的类.尽管不是必需的,但建议这样做.

You should also change the rest of the code to use the newer classes. Although not required, it is recommended to do so.

这篇关于删除文件夹中部分文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆