2017-02-04 127 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