简体   繁体   中英

Remove a Specific Line From text file

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.

Output: Please delete: d Blueberry Remove:Blueberry

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

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:

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

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

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/O and The try-with-resources Statement for some more details

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM