为什么我既不能删除也不能重命名文件?

为什么我既不能删除也不能重命名文件?

问题描述:

在为我的课程创建方法时,我遇到了意想不到的问题。我尝试过其他方面的解决方案,但他们不适合我。我的方法应该只是找到指定的行,复制文件跳过不必要的行,删除原始文件,并将临时文件重命名为原始文件的名称。它会按预期成功创建新文件,但因为无法将临时文件重命名为原始文件而无法删除前一个文件。我无法弄清楚,为什么?为什么我既不能删除也不能重命名文件?

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

你有什么异常吗? – TDG

+0

发布的代码甚至没有编译。 tempFile未定义。发布实际的代码,确实存在问题。使用Files.delete和Files.move:你会得到解决问题的解决办法。 –

+0

不,我没有得到任何异常,并且对tempFile感到抱歉,忘记将它改为temp。我编辑了原始代码,以便变量更清晰。 –

试试这个代码:

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

在我运行该方法之前文件file_name.txt是否已经存在,并且它包含多行可以更改任何内容? 而temp.renameTo()是一个File类型的方法,并且不能在其中使用诸如“.txt”之类的字符串。 –

+0

不是的。问题是,在删除前一个文件后,只调用一种方法将文件重命名为另一个文件的名称。既然你说你的逻辑是好的,临时文件得到你想要的输出,你唯一需要做的就是我发布在我的答案 – Ricardo

+0

其实,我不会像你这样做。如果你正在给一个已经存在的文件名,你应该使用File.open,然后检查它是否存在,如果它存在,请执行你的逻辑 – Ricardo

我可以提出几个原因的删除和/或重命名可能会失败,但有一个更好的办法来解决你的问题不是猜测 。

如果您使用PathFiles.delete(Path)Files.move(Path, Path, CopyOption...)方法,它们将在操作失败时引发异常。例外的名称和消息应该给你提供什么实际上出错的线索。

javadoc是herehere


1 - 下面是一些猜测:1)文件已在其他地方开了,它已被锁定的结果。 2)您无权删除文件。