删除其中包含特定字符串的文本行

时间:2015-03-11 15:13:59

标签: java

我正在尝试从文件中删除文本行。到目前为止,我有这个,但它给了我一些问题。如果在行上的初始文本之后没有任何内容,则它可以工作。但是如果在文本文件中我在Bart之后有任何东西,例如巴特琼斯,它将不会删除该行,它将只是不管它。请帮忙。

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

} `

4 个答案:

答案 0 :(得分:1)

而不是.equals(lineToRemove)使用.contains(lineToRemove)

答案 1 :(得分:1)

只需更改

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

if (!line.indexOf(lineToRemove) > -1)
  • 无需修剪,因为您只想知道字符串是否在行中。
  • indexOf生成的字节码少于contains,因为其中包含自己调用indexOf和其他修剪。
  • 如果您对案件不重要,可能需要使用toLowerCase进行比较。

有关与indexOfcontains进行比较的详情,请参阅Is String.Contains() faster than String.IndexOf()?

答案 2 :(得分:1)

您需要在此行中不使用equalscontains

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

像这样:

if (!line.contains(lineToRemove)) {

答案 3 :(得分:1)

它与您在文件中搜索字符串的方式有关。目标是删除“包含”字符串的行,而不是“等于”字符串。更改循环中的if语句应该可以解决问题。

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

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

请注意,我还添加了对toLowerCase()的调用,以防搜索字符串和行内容在不同情况下,您可能也想删除它们。如果不是这种情况,您可以安全地删除这些电话。