简体   繁体   English

删除其中带有特定字符串的一行文本

[英]Deleting a line of text with a certain string inside of it

I am trying to delete a text line from a file. 我正在尝试从文件中删除文本行。 So far I have this but it is giving me some problems. 到目前为止,我已经有了这个,但是它给了我一些问题。 It works if there is nothing after the initial text on the line. 如果该行的初始文本之后没有任何内容,则可以使用。 But if in the text file I have anything after Bart ie Bart Jones for example, it will not delete the line, it will just leave it alone. 但是,如果在文本文件中,例如在Bart即Bart Jones之后有其他内容,它将不会删除该行,而只会保留它。 Please help. 请帮忙。

public void removeLineFromFile(String file, String lineToRemove) {

    try {

        File inFile = new File(file);

        if (!inFile.isFile()) {
            System.out.println("Parameter is not an existing file");
            return;
        }

        //Construct the new file that will later be renamed to the original filename.
        File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

        BufferedReader br = new BufferedReader(new FileReader(file));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

        String line = null;

        //Read from the original file and write to the new
        //unless content matches data to be removed.
        while ((line = br.readLine()) != null) {

            if (!line.trim().equals(lineToRemove)) {

                pw.println(line);
                pw.flush();
            }
        }
        pw.close();
        br.close();

        //Delete the original file
        if (!inFile.delete()) {
            System.out.println("Could not delete file");
            return;
        }

        //Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(inFile))
            System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    catch (IOException ex) {
        ex.printStackTrace();
    }
}

public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.removeLineFromFile("booklist.txt", "bart");
}

} ` }`

代替.equals(lineToRemove)使用.contains(lineToRemove)

Simply change 只需更改

if (!line.trim().equals(lineToRemove))

with

if (!line.indexOf(lineToRemove) > -1)
  • There is no need to trim as you only want to know if the string is in the line. 无需修剪,因为您只想知道字符串是否在行中。
  • indexOf generate less bytecode then contains as contains itself call indexOf with other trims. indexOf生成较少的字节码,然后contains本身包含其他修整的indexOf调用。
  • You might want to compare using toLowerCase if you don't matter of the case. 如果不需要,可以使用toLowerCase进行比较。

See Is String.Contains() faster than String.IndexOf()? 请参阅String.Contains()是否比String.IndexOf()快? for more info on comparing with indexOf vs contains . 有关与indexOfcontains进行比较的更多信息。

You need to use not equals but contains in this line: 您需要在此行中使用not equalscontains

if (!line.trim().equals(lineToRemove)) {

Like this: 像这样:

if (!line.contains(lineToRemove)) {

It has to do with the way you're searching for the string in the file. 它与您在文件中搜索字符串的方式有关。 The goal is to delete a line "containing" a string, not "equals to" a string. 目的是删除“包含”字符串而不是“等于”字符串的行。 Changing the if statement in the loop should do the trick. 在循环中更改if语句应该可以解决问题。

 if (!line.trim().toLowerCase().contains(lineToRemove.toLowerCase())) {

            pw.println(line);
            pw.flush();
        }

Notice that I also added a call to toLowerCase() in case the search string and line content where in different cases, you'd probably want to delete them as well. 请注意,我还向toLowerCase()添加了一个调用,以防搜索字符串和行内容在不同情况下也可能要删除它们。 If that's not the case, you can safely remove those calls. 如果不是这种情况,则可以安全地删除这些呼叫。

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

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