在Java中重命名文件的最佳方法,有大约500个文件在目录中。

12

我有一个文件夹里有500个pdf文件。 我想要删除文件名前五个字符并将其重命名。


8
最好的方法是不使用Java,而是使用bash或脚本语言。 - Pascal Thivent
1
这个代码能解决问题吗?不用JAVA btw ...................... dir /B > fileList.txt for /f "tokens=1,2,3" %i in (fileList.txt) DO ren "%i %j %l" %l - Narayan
8个回答

22

以下是一个示例代码,用于重命名给定目录中文件的列表。在下面的示例中,c:\Projects\sample 是文件夹,列出的文件已被重命名为0.txt、1.txt、2.txt等。

希望这可以解决您的问题。

import java.io.File;
import java.io.IOException;

public class FileOps {


    public static void main(String[] argv) throws IOException {

        File folder = new File("\\Projects\\sample");
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {

                File f = new File("c:\\Projects\\sample\\"+listOfFiles[i].getName()); 

                f.renameTo(new File("c:\\Projects\\sample\\"+i+".txt"));
            }
        }

        System.out.println("conversion is done");
    }
}

13

这样应该可以做到(Windows版本):

import java.io.*;

public class RenameFile {
    public static void main(String[] args) {
        // change file names in 'Directory':
        String absolutePath = "C:\\Dropbox\\java\\Directory";
        File dir = new File(absolutePath);
        File[] filesInDir = dir.listFiles();
        int i = 0;
        for(File file:filesInDir) {
            i++;
            String name = file.getName();
            String newName = "my_file_" + i + ".pdf";
            String newPath = absolutePath + "\\" + newName;
            file.renameTo(new File(newPath));
            System.out.println(name + " changed to " + newName);
        }
    } // close main()
} // close class

4
使用File.listFiles(...)列出目录中的文件,使用String.substring(...)形成新的文件名,并使用File.rename(...)进行重命名。但是在开始重命名之前,建议您的应用程序检查它是否可以重命名所有文件而不会发生冲突。
但是@Pascal的评论很正确。Java不是做这种事情最简单的工具。

1
根据您的要求,可以使用Java来实现以下操作:
//path to folder location
String filePath = "C:\\CMS\\TEST";

//create direcotory TEST
File fileDir = new File(filePath);

if (!fileDir.exists()) {
   fileDir.mkdirs();
}

//create two file named 12345MyFile1.pdf, 12345MyFile2.pdf
File file1 = new File(filePath, "\\12345MyFile1.pdf");
file1.createNewFile();
File file2 = new File(filePath, "\\12345MyFile2.pdf");
file2.createNewFile();

//rename the file
File file = new File(filePath);
String[] fileList = file.list();//get file list in the folder

for (String existFileName : fileList) {
   String newFileName = existFileName.substring(5);//remove first 5 characters

   File sourceFile = new File(filePath + File.separator + existFileName);
   File destFile = new File(filePath + File.separator + newFileName);

   if (sourceFile.renameTo(destFile)) {
       System.out.println("File renamed successfully from: " + existFileName + " to: " + newFileName);
   } else {
       System.out.println("Failed to rename file");
   }
}

0

这将更改您提到的所有文件夹的文件名:

for (int i = 0; i < folders.length; i++) {
    File folder = new File("/home/praveenr/Desktop/TestImages/" + folders[i]);
    File[] files2 = folder.listFiles();

    int count = 1;
    for (int j = 0; j <files2.length; j++,count++) {
        System.out.println("Old File Name:" + files2[j].getName());
        String newFileName = "/home/praveenr/Desktop/TestImages/" + folders[i]+"/file_"+count+"_original.jpg";
        System.out.println("New FileName:" + newFileName);
        files2[j].renameTo(new File(newFileName));
    }

}

0

Java不是这种工作的好选择。更好的选择是像Groovy这样的JVM脚本语言。如果您想追求这个选项

步骤1:

下载并安装Groovy

步骤2:

启动Groovy控制台

步骤3:

运行此脚本

def dirName = "/path/to/pdf/dir"

new File(dirName).eachFile() { file -> 
    def newName = file.getName()[5..-1]
    File renamedFile = new File(dirName + "/" + newName)
    file.renameTo(renamedFile)

    println file.getName() + " -> " + renamedFile.getName() 
}     

我在这里假设所有文件都在目录 /path/to/pdf/dir 中。如果其中一些文件位于此目录的子目录中,则使用 File.eachFileRecurse 而不是 File.eachFile


+1 因为我认为这个答案不应该被给予三个负评,尤其是没有任何解释的情况下。 - Pascal Thivent
请问您能否证明一下您的观点?这真的取决于他想要什么。如果他需要一个基于GUI的应用程序,Java就可以。 - captainspi
1
@SPI 我假设(也许不正确)这是一次性任务。 - Dónal
+1 因为如果这是一个一次性任务,你的解决方案可能是最合适的! - captainspi
最好使用Java程序或命令提示符进行操作,无需下载额外的内容。 - Shivendra Prakash Shukla

0
如果您使用的是MacOS X,并且想要重命名外部驱动器中文件夹和子文件夹中的所有文件,下面的代码可以完成此任务:
public class FileOps {

    public static void main(String[] argv) throws IOException {
        String path = "/Volumes/FAT32/direito_administrativo/";
        File folder = new File(path);
        changeFilesOfFolder(folder);
    }

    public static void changeFilesOfFolder(File folder) {
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            int count = 1;
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    File f = new File(folder.getPath() + "/" + listOfFiles[i].getName()); 
                    f.renameTo(new File(folder.getPath() + "/" + count + ".flv"));
                    count++;                    
                } else if (listOfFiles[i].isDirectory()) {
                    changeFilesOfFolder(listOfFiles[i]);
                }
            }
        } else {
            System.out.println("Path without files");
        }
    }
}

0

如果你使用的是Windows系统,建议使用命令提示符或.bat文件。Windows在操作系统级别原生支持通配符重命名,因此比Java快得多,后者必须遍历所有名称并为每个名称发出重命名调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接