2017-02-04 108 views
1

我試圖從文件中刪除特定行。但我在從文本文件中刪除特定行時遇到了問題。讓我們說,我的文本文件,我想下面的刪除藍莓文件中:從文本文件中刪除特定行

舊列表的文本文件:

Chocolate 
Strawberry 
Blueberry 
Mango 

新列表的文本文件:

Chocolate 
Strawberry 
Mango 

我試圖運行我的Java程序,當我輸入刪除,並沒有刪除文本文件中的行。

輸出: 請刪除: d 藍莓 刪除:藍莓

當我打開我的文本文件,它繼續以詞「藍莓」只循環。

文本文件:

Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 

我的問題是如何刪除文本文件中的特定行?

這裏是我的Java代碼:

String input="Please delete: "; 
System.out.println(input); 

try 
     {   
      BufferedReader reader = new BufferedReader 
        (new InputStreamReader (System.in)); 
      line = reader.readLine(); 

      String inFile="list.txt"; 
      String line = ""; 


      while(!line.equals("x")) 
      { 
       switch(line) 
       {     

        case "d": 

        line = reader.readLine(); 
        System.out.println("Remove: " + line); 
        String lineToRemove=""; 

        FileWriter removeLine=new FileWriter(inFile); 
        BufferedWriter change=new BufferedWriter(removeLine); 
        PrintWriter replace=new PrintWriter(change); 

        while (line != null) { 
         if (!line.trim().equals(lineToRemove)) 
         { 
          replace.println(line); 
          replace.flush(); 
         } 
        } 
        replace.close(); 
        change.close(); 
        break; 

       } 
       System.out.println(input); 
       line = reader.readLine(); 


      } 

     } 
     catch(Exception e){ 
      System.out.println("Error!"); 
     } 
+0

你只讀過第一行,你永遠不會讀取文件中的任何其他行...... – MadProgrammer

+1

我看不到你將'lineToRemove'設置爲空白以外的任何地方。您應該將lineToRemove設置爲用戶輸入的行。 –

回答

1

讓我們快速瀏覽一下你的代碼...

line = reader.readLine(); 
//... 
while (line != null) { 
    if (!line.trim().equals(lineToRemove)) 
    { 
     replace.println(line); 
     replace.flush(); 
    } 
} 

基本上,你讀文件的第一行,然後反覆進行比較與lineToRemove,永遠。此循環永遠不會退出

這是一個概念證明,您需要根據需要對其進行修改。

基本上,你需要確保你正在做的,就是你正在閱讀的輸入文件的每一行,直到沒有更多的行

// All the important information 
String inputFileName = "..."; 
String outputFileName = "..."; 
String lineToRemove = "..."; 
// The traps any possible read/write exceptions which might occur 
try { 
    File inputFile = new File(inputFileName); 
    File outputFile = new File(outputFileName); 
    // Open the reader/writer, this ensure that's encapsulated 
    // in a try-with-resource block, automatically closing 
    // the resources regardless of how the block exists 
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); 
      BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { 
     // Read each line from the reader and compare it with 
     // with the line to remove and write if required 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      if (!line.equals(lineToRemove)) { 
       writer.write(line); 
       writer.newLine(); 
      } 
     } 
    } 

    // This is some magic, because of the compounding try blocks 
    // this section will only be called if the above try block 
    // exited without throwing an exception, so we're now safe 
    // to update the input file 

    // If you want two files at the end of his process, don't do 
    // this, this assumes you want to update and replace the 
    // original file 

    // Delete the original file, you might consider renaming it 
    // to some backup file 
    if (inputFile.delete()) { 
     // Rename the output file to the input file 
     if (!outputFile.renameTo(inputFile)) { 
      throw new IOException("Could not rename " + outputFileName + " to " + inputFileName); 
     } 
    } else { 
     throw new IOException("Could not delete original input file " + inputFileName); 
    } 
} catch (IOException ex) { 
    // Handle any exceptions 
    ex.printStackTrace(); 
} 

看看Basic I/OThe try-with-resources Statement一些更多詳細信息

0

從控制檯讀取輸入,讀取文件和寫入文件需要區分並單獨完成。您無法同時讀寫文件。你甚至不讀你的文件。您只是在您的while循環中無限期比較您的控制檯輸入。實際上,您甚至沒有將lineTobeRemoved設置爲輸入行。這是做到這一點的一種方式。

算法:

讀控制檯輸入(您的行刪除),然後開始讀取文件和尋找線將其與你的輸入線比較刪除。如果行不匹配,則將讀取的行存儲在一個變量中,否則會拋出此行,因爲您想刪除它。 完成閱讀後,開始在文件上寫入存儲的行。現在,您將刪除一行更新的文件。

public static void main(String args[]) { 
    String input = "Please delete: "; 
    System.out.println(input); 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       System.in)); 
     String line = reader.readLine(); 
     reader.close(); 

     String inFile = "list.txt"; 


       System.out.println("Remove: " + line); 
       String lineToRemove = line; 


       StringBuffer newContent = new StringBuffer(); 

       BufferedReader br = new BufferedReader(new FileReader(inFile)); 
       while ((line = br.readLine()) != null) { 
        if (!line.trim().equals(lineToRemove)) { 
         newContent.append(line); 
         newContent.append("\n"); // new line 

        } 
       } 
        br.close(); 

       FileWriter removeLine = new FileWriter(inFile); 
       BufferedWriter change = new BufferedWriter(removeLine); 
       PrintWriter replace = new PrintWriter(change); 
       replace.write(newContent.toString()); 
       replace.close(); 

    } 

    catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
+0

最後的'if(br.readLine()== null)'測試是毫無意義的。它不能是其他任何東西,因爲它已經在while循環中返回null了。如果它神奇地沒有返回null,那麼你就會把它扔掉,永遠不會關閉輸出。 – EJP

+0

@EJP沒錯。我更新它。 – hhafeez

+0

另外要注意'\ n'不適用於或平臺;) – MadProgrammer