2016-04-29 85 views
1

在爲我的課程創建方法時,我遇到了意想不到的問題。我嘗試過其他方面的解決方案,但他們不適合我。我的方法應該只是找到指定的行,複製文件跳過不必要的行,刪除原始文件,並將臨時文件重命名爲原始文件的名稱。它會按預期成功創建新文件,但因爲無法將臨時文件重命名爲原始文件而無法刪除前一個文件。我無法弄清楚,爲什麼?爲什麼我既不能刪除也不能重命名文件?

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。我編輯了原始代碼,以便變量更清晰。 –

回答

1

試試這個代碼:

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

1

我可以提出幾個原因的刪除和/或重命名可能會失敗,但有一個更好的辦法來解決你的問題不是猜測 。

如果您使用PathFiles.delete(Path)Files.move(Path, Path, CopyOption...)方法,它們將在操作失敗時引發異常。例外的名稱和消息應該給你提供什麼實際上出錯的線索。

javadoc是herehere


1 - 下面是一些猜測:1)文件已在其他地方開了,它已被鎖定的結果。 2)您無權刪除文件。

相關問題