为什么我既不能删除也不能重命名文件?
问题描述:
在为我的课程创建方法时,我遇到了意想不到的问题。我尝试过其他方面的解决方案,但他们不适合我。我的方法应该只是找到指定的行,复制文件跳过不必要的行,删除原始文件,并将临时文件重命名为原始文件的名称。它会按预期成功创建新文件,但因为无法将临时文件重命名为原始文件而无法删除前一个文件。我无法弄清楚,为什么?为什么我既不能删除也不能重命名文件?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
答
试试这个代码:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
你有什么异常吗? – TDG
发布的代码甚至没有编译。 tempFile未定义。发布实际的代码,确实存在问题。使用Files.delete和Files.move:你会得到解决问题的解决办法。 –
不,我没有得到任何异常,并且对tempFile感到抱歉,忘记将它改为temp。我编辑了原始代码,以便变量更清晰。 –