我正在尝试实现 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/