从文本文件中删除特定行

时间:2017-02-04 02:45:58

标签: java

我尝试从文件中删除特定行。但是我在从文本文件中删除特定行时遇到问题。我们说,我的文本文件我想删除以下文件中的蓝莓:

旧列表文本文件:

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!");
        }

2 个答案:

答案 0 :(得分: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了解更多详情

答案 1 :(得分: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();
    }

}