java 从文本文件中删除特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42035929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:18:11  来源:igfitidea点击:

Remove a Specific Line From text file

java

提问by Mubarak Manan

I trying to remove a specific line from a file. But I have a problem in deleting a particular line from the text file. Let's said, my text file I want to remove Blueberry in the file following:

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

Old List Text file:

旧列表文本文件:

Chocolate
Strawberry
Blueberry
Mango

New List Text file:

新列表文本文件:

Chocolate
Strawberry
Mango

I tried to run my Java program, when I input for delete and it didn't remove the line from the text file.

我试图运行我的 Java 程序,当我输入删除时,它没有从文本文件中删除该行。

Output: Please delete: d Blueberry Remove:Blueberry

输出:请删除:d Blueberry 删除:Blueberry

When I open my text file, it keep on looping with the word "Blueberry" only.

当我打开我的文本文件时,它只用“Blueberry”这个词继续循环。

Text file:

文本文件:

Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry

My question is how to delete the specific line from the text file?

我的问题是如何从文本文件中删除特定行?

Here is my Java code:

这是我的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!");
        }

回答by MadProgrammer

Let's take a quick look at your code...

让我们快速浏览一下您的代码...

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

Basically, you read the first line of the file and then repeatedly compare it with the lineToRemove, forever. This loop is never going to exit

基本上,您阅读文件的第一行,然后反复将其与lineToRemove,进行比较。这个循环永远不会退出

This is a proof of concept, you will need to modify it to your needs.

这是一个概念证明,您需要根据需要对其进行修改。

Basically, what you need to ensure you're doing, is you're reading each line of the input file until there are no more lines

基本上,你需要确保你在做什么,是你正在阅读输入文件的每一行,直到没有更多的行

// 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();
}

Have a look at Basic I/Oand The try-with-resources Statementfor some more details

查看基本 I/Otry-with-resources 语句以了解更多详细信息

回答by hhafeez

Reading input from console, reading file and writing to a file needs to be distinguished and done separately. you can not read and write file at the same time. you are not even reading your file. you are just comparing your console input indefinitely in your while loop.In fact, you are not even setting your lineTobeRemoved to the input line. Here is one way of doing it.

从控制台读取输入,读取文件和写入文件需要区分并单独完成。您不能同时读取和写入文件。你甚至没有阅读你的文件。您只是在 while 循环中无限期地比较控制台输入。事实上,您甚至没有将 lineTobeRemoved 设置为输入行。这是一种方法。

Algorithm:

算法:

Read the console input (your line to delete) then start reading the file and looking for line to delete by comparing it with your input line. if the lines do not match match then store the read line in a variable otherwise throw this line since you want to delete it. Once finished reading, start writing the stored lines on the file. Now you will have updated file with one line removed.

读取控制台输入(要删除的行),然后开始读取文件并通过将其与输入行进行比较来查找要删除的行。如果行不匹配,则将读取的行存储在变量中,否则抛出此行,因为您想删除它。完成读取后,开始在文件中写入存储的行。现在您将更新文件并删除一行。

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();
    }

}