简体   繁体   English

从文本文件中删除特定行

[英]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. 当我输入要删除的内容并且没有从文本文件中删除该行时,我尝试运行我的Java程序。

Output: Please delete: d Blueberry Remove:Blueberry 输出:请删除:d蓝莓删除:蓝莓

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

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. 基本上,您先读取文件的第一行,然后将其与lineToRemove永远重复比较。 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 查看Basic I / Otry-with-resources语句以获取更多详细信息

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. 您只是在while循环中无限期地比较控制台输入。实际上,您甚至都没有将lineTobeRemoved设置为输入行。 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();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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