java中重命名文件的最佳方法,一个目录中有大约500个文件
我的目录中有 500 个 pdf 文件。我想删除文件名的前五个字符并重命名。
I have 500 pdf files in a directory. I want to remove first five characters of a filename and rename it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
用于重命名给定目录中的文件列表的示例代码。在下面的示例中,
c:\Projects\sample
是文件夹,下面列出的文件已重命名为 0.txt、1.txt、2.txt 等。我希望这样会解决你的问题
Sample code for you to rename the List of files in a given directory. In the below example,
c:\Projects\sample
is the folder, the files which are listed under that have been renamed to 0.txt, 1.txt, 2.txt, etc.I hope this will solve your problem
像这样的事情应该做(Windows版本):
something like this should do (Windows version):
使用
File.listFiles(...)
列出目录中的文件,使用String.substring(...)
形成新文件名,并使用File.rename(...)
进行重命名。但我建议您在开始重命名之前,先检查您的应用程序是否可以重命名所有文件,而不会发生任何冲突。
但@Pascal 的评论是正确的。 Java 并不是做这种事情的最简单的工具。
Use
File.listFiles(...)
to list the files in the directory,String.substring(...)
to form the new file names, andFile.rename(...)
to do the renaming.But I suggest that you have your application check that it can rename all of the files without any collisions before you start the renaming.
But @Pascal's comment is spot on. Java is not the simplest tool for doing this kind of thing.
根据您的要求,使用java可以实现如下所示,
As in your requirement, using java can achieve this like follows,
如果您使用的是 Windows,则应使用命令提示符或 .bat 文件。 Windows 在操作系统级别原生支持通配符重命名,因此它比 Java 快几个数量级,Java 必须迭代所有名称并为每个名称发出重命名调用。
If you're on Windows you should use the command prompt or a .bat file. Windows supports wildcard renames natively at the OS level so it will be orders of magnitude faster than Java, which has to iterate over all the names and issue rename calls for each one.
对于此类工作,Java 是一个糟糕的选择。更好的选择是像 Groovy 这样的 JVM 脚本语言。如果您想选择此选项
第 1 步:
下载并安装 Groovy
第 2 步:
启动 groovy 控制台
第 3 步:
运行此脚本
I'我假设所有文件都位于目录
/path/to/pdf/dir
中。如果其中一些文件位于此目录的子目录中,则使用File.eachFileRecurse
而不是File.eachFile
。Java is a bad choice for this kind of work. A much better choice would be a JVM scripting language like Groovy. If you want to pursue this option
Step 1:
Download and install Groovy
Step 2:
Start the groovy console
Step 3:
Run this script
I'm assuming here that all the files are in the directory
/path/to/pdf/dir
. If some of them are in subdirectories of this directory, then useFile.eachFileRecurse
instead ofFile.eachFile
.如果您使用的是 MacOS X 并且想要重命名外部驱动器中的文件夹和子文件夹内的所有文件,下面的代码可以完成此任务:
If you're on MacOS X and want to rename all files inside folders and subfolder from an External Drive, the code below will do the job:
这将更改您提到的文件夹的所有文件名:
This will change all the file names of the folders you mentioned: