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

发布于 2024-08-30 09:18:03 字数 45 浏览 14 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

情愿 2024-09-06 09:18:03

用于重命名给定目录中的文件列表的示例代码。在下面的示例中,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");
    }
}

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

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");
    }
}
酸甜透明夹心 2024-09-06 09:18:03

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

something like this should do (Windows version):

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
活泼老夫 2024-09-06 09:18:03

使用 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, and File.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.

海的爱人是光 2024-09-06 09:18:03

根据您的要求,使用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");
   }
}

As in your requirement, using java can achieve this like follows,

//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");
   }
}
森罗 2024-09-06 09:18:03

如果您使用的是 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.

夜雨飘雪 2024-09-06 09:18:03

对于此类工作,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() 
}     

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

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.eachFileRecurse instead of File.eachFile.

别想她 2024-09-06 09:18:03

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

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:

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");
        }
    }
}
凉城凉梦凉人心 2024-09-06 09:18:03

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

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

}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文