java中重命名文件的最佳方法,一个目录中大约有500个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2720578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:04:41  来源:igfitidea点击:

best way in java to rename a file , there are about 500 files in a directory

javafile-rename

提问by Suresh S

I have 500 pdf files in a directory. I want to remove first five characters of a filename and rename it.

我在一个目录中有 500 个 pdf 文件。我想删除文件名的前五个字符并重命名。

回答by Stephen C

Use File.listFiles(...)to list the files in the directory, String.substring(...)to form the new file names, and File.rename(...)to do the renaming.

使用File.listFiles(...)列出目录中的文件,String.substring(...)从而形成新的文件名,并File.rename(...)做了重新命名。

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.

但@Pascal 的评论是正确的。Java 并不是做这种事情的最简单的工具。

回答by Dónal

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

对于这种工作,Java 是一个糟糕的选择。一个更好的选择是像 Groovy 这样的 JVM 脚本语言。如果你想追求这个选项

Step 1:

第1步:

Download and install Groovy

下载并安装 Groovy

Step 2:

第2步:

Start the groovy console

启动 groovy 控制台

Step 3:

第 3 步:

Run this script

运行这个脚本

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() 
}     

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 use File.eachFileRecurseinstead of File.eachFile.

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

回答by user207421

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.

如果您使用的是 Windows,则应使用命令提示符或 .bat 文件。Windows 在操作系统级别原生支持通配符重命名,因此它比 Java 快几个数量级,Java 必须迭代所有名称并为每个名称发出重命名调用。

回答by gmhk

Sample code for you to rename the List of files in a given directory. In the below example, c:\Projects\sampleis the folder, the files which are listed under that have been renamed to 0.txt, 1.txt, 2.txt, etc.

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

I hope this will solve your problem

我希望这能解决你的问题

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");
    }
}

回答by Egnatius

something like this should do (Windows version):

这样的事情应该做(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

回答by Rodrigo

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:

如果您使用的是 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");
        }
    }
}

回答by Ravipati Praveen

This will change all the file names of the folders you mentioned:

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

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));
    }

}

回答by Shiva

Well, try this sample code

好吧,试试这个示例代码

import java.io.File;

public class RenameFile
{ 
   public String callRename(String flname, String fromName, String toName)
   {
      try
      {
         File fe = new File(flname);
         File allFile[] = fe.listFiles();
         for(int a = 0; a < allFile.length; a++)
         {
            String presentName = (allFile[a].toString().replaceAll(fromName, toName));
            allFile[a].renameTo(new File(presentName));
         }
         return allFile + " files renamed successfully.!!!";
      }
      catch(Exception ae)
      {
         return(ae.getMessage());
      }
   }

   public static void main(String[] args)
   {
      RenameFile rf = new RenameFile();
      System.out.println("Java rename files in directory : ");
      String lastResult = rf.callRename("yourpathname", "from", "to");
      System.out.println(lastResult);
   }
}