我正在尝试实现POP3协议功能,我想使用文件系统(其中的目录和文本文件)作为存储电子邮件的数据库。为此,我需要在每次访问数据库时重新编号.txt文件(email1.txt,email2.txt,..),以检查天气是否已删除任何电子邮件。假设email2.txt已被删除,这意味着在下一个交易中,所有电子邮件都将重新编号,email3.txt将重命名为email2.txt,email4将成为email3,依此类推。如果没有删除它们,则所有文件应保持不变
我尝试使用以下代码,但它不起作用。但是,它适用于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);
}
答案 0 :(得分:0)
您好我对您的代码进行了此更改:
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上测试它:)
答案 1 :(得分:0)
嗯,我以为你可以查找所有文件,看看它们是否存在并做任何你想做的事情看起来像这样:O当然我还没有完成它但也许它可以帮助你=)
public static void main(String[] args) {
String absolutePath = "/Users/jucepho/Desktop/src/other/";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
List<File> filesDirectory = Arrays.asList(filesInDir);
List<Integer> numbersUsed = new ArrayList<Integer>();
for(File files2: filesDirectory ){
String nameFile = files2.getName();
System.out.println(nameFile);
String regex = "email.\\.txt";
boolean dosItMatch = nameFile.matches(regex);
if(dosItMatch){
String number = "\\d+";
numbersUsed.add(Integer.valueOf(regex.replace("email", "").replace("\\.txt", "")));
}
System.out.println(dosItMatch);
}
System.out.println(numbersUsed);
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);
}
}
答案 2 :(得分:0)
最后,我首先通过排序(filesInDir)数组来摆脱它。
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
Arrays.sort(filesInDir);
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
s.getBasicRemote().sendText("+OK "+oldName);
oldName = absolutePath + "/"+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + "/"+ newName;
s.getBasicRemote().sendText("+OK "+newName);
File newFile =new File(newName);
oldFile.renameTo(newFile);
}