java - 如何使用java重命名linux目录中的所有文件?

标签 java linux java-io file-rename

我正在尝试实现 POP3 协议(protocol)功能,我想使用文件系统(其中的目录和文本文件)作为数据库来存储电子邮件。为此,我需要在每次访问数据库时对 .txt 文件(email1.txt、email2.txt、..)重新编号,以检查是否有任何电子邮件被删除。假设 email2.txt 已被删除,这意味着在下一次交易中,所有电子邮件都将重新编号,email3.txt 将重命名为 email2.txt,email4 变为 email3 ans 等等。如果它们都没有被删除,那么所有文件都应该保持不变

我尝试使用以下代码,但它不起作用。但是,它适用于 Windows。我知道,重命名文件取决于操作系统。

    File dir = new File(absolutePath);
    File[] filesInDir = dir.listFiles();
    int i = 0;
        for(File file1:filesInDir) {
        i++;
        String oldName = file1.getName();
        oldName = absolutePath + "/" + oldName;
        File oldFile=new File(oldName);
        String newName = "email" + i + ".txt";
        newName = absolutePath + "/" + newName;
        File newFile =new File(newName);
        oldFile.renameTo(newFile);
    }

最佳答案

您好,我对您的代码做了以下更改:

    public static void main(String[] args) {

    String absolutePath = "/Users/jucepho/Desktop/ReaderPaths/src/other/";

    File dir = new File(absolutePath);
    File[] filesInDir = dir.listFiles();
    int i = 0;
        for(File file1:filesInDir) {
        i++;
        String oldName = file1.getName();
        oldName = absolutePath + File.separator+ oldName;
        File oldFile=new File(oldName);
        String newName = "email" + i + ".txt";
        newName = absolutePath + File.separator+ newName;
        File newFile =new File(newName);
        oldFile.renameTo(newFile);
    }

}

它将我目录中的所有文件重命名为 email1.txt email2.txt 等....

它应该可以工作,我在 Ubuntu 上测试过 :)

关于java - 如何使用java重命名linux目录中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42740611/

相关文章:

java - 带有@Controller 注解的类是一个单独的对象吗?

sql-server - 在 Linux 上迁移到新的 SQL Server 2017

Android 将字符串写入文件花费的时间太长

Java/Groovy&Grails 文件写入

java - 为什么可以在 java 中使用 java.security.SecurityManager 读取任何文件?

java - 文件的 Junit 测试用例

java - 过度使用异常处理的程序模型在速度方面是否高效?

java - "Mistaken"计算结果。 java 。如此卡住

python - 如何使用Python子进程模块从Linux终端读取数据

linux - Shell:列出按文件数排序的目录(包括子目录)