简体   繁体   English

在文本文件中查找字符串,删除行和下面的行

[英]Find String in text file, delete line and ones below

I have a bit of code to find a string in a text file, print the line the string is on and then print the 5 lines below it. 我有一些代码在文本文件中找到一个字符串,打印字符串所在的行,然后打印它下面的5行。 However, I need to modify it so that instead of printing, it deletes/removes the line after the string is found. 但是,我需要对其进行修改,以便在找到字符串后删除/删除行而不是打印。 How would I go about doing this? 我该怎么做呢?

File file = new File("./output.txt");
Scanner in = null;
try {
    in = new Scanner(file);
    while (in.hasNext()) {
        String line = in.nextLine();
        if (line.contains("(1)")) {
            for (int a = 0; in.hasNextLine() && a < 6; a++) {
                System.out.println(line);
                line = in.nextLine();
            }
        }
    }
} catch (Exception e) {
}

Find a small snippet you can start with. 找一个你可以开始的小片段。

Assuming your question.txt has the following input. 假设您的question.txt具有以下输入。

line 1
line 2
line 3 (1)
line 4
line 5
line 6
line 7
line 8
line 9
line 10

This snippet will print all lines and skip the line line 3 (1) as well the five lines after. 此片段将打印所有行并跳过第line 3 (1)以及之后的5行。

List<String> lines = Files.readAllLines(Paths.get("question.txt"), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i++) {
    if (lines.get(i).contains("(1)")) {
        i = i + 6;
    }
    System.out.println(lines.get(i));
}

output 产量

line 1
line 2
line 9
line 10

To store the lines into the file is left for you. 将行存储到文件中是留给您的。

My Suggestion is you first declare and initialise a StringBuilder say output before your above code like: 我的建议是你首先在上面的代码之前声明并初始化一个StringBuilderoutput ,如:

StringBuilder output = new StringBuilder();

Now after the close of the if statement before the closing of the while loop append the line to the output and add a "\\n" at the end like this: 现在,在关闭while循环之前关闭if语句后,将该行附加到output并在末尾添加"\\n" ,如下所示:

output.append(line+"\n");

Now finally after your code that you have posted create a FileWriter say writer and then use the writer to write the output as shown below: 现在,最后你的代码,你已经张贴创建后FileWriterwriter ,然后用作家写的output ,如下图所示:

try(FileWriter writer = new FileWriter(file, false)){
   writer.write(output);
}catch IOException(e){
   e.printStackTrace();
}

Also don't forget to remove or comment out the following line if you do not want them printed in the output. 如果您不希望在输出中打印它们,也不要忘记删除或注释掉以下行。

System.out.println(line);

SubOtimal has a good, concise answer that will work for most cases. SubOtimal有一个很好的,简洁的答案,适用于大多数情况。 The following is more complex but avoids loading the whole file into memory. 以下更复杂但避免将整个文件加载到内存中。 That probably isn't an issue for you but just in case... 这对你来说可能不是问题,但以防万一......

public void deleteAfter(File file, String searchString, int lineCountToDelete) {
    // Create a temporary file to write to
    File temp = new File(file.getAbsolutePath() + ".tmp");
    try (BufferedReader reader = new BufferedReader(new FileReader(file));
         PrintWriter writer = new PrintWriter(new FileWriter(temp)) ) {

        // Read up to the line we are searching for
        // and write each to the temp file
        String line;
        while((line = reader.readLine()) != null && !line.equals(searchString)){
            writer.println(line);
        }

        // Skip over the number of lines we want to "delete"
        // as well as watching out for hitting the end of the file
        for(int i=0;i < lineCountToDelete && line != null; i++){
            line = reader.readLine();
        }

        // Write the remaining lines to the temp file.
        while((line = reader.readLine()) != null){
            writer.println(line);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to delete the lines",e);
    }

    // Delete the original file
    if(!file.delete()){
        throw new IllegalStateException("Unable to delete file: " + file.getAbsolutePath());
    }

    // Rename the temp file to the original name
    if(!temp.renameTo(file)){
        throw new IllegalStateException("Unable to rename " +
                temp.getAbsolutePath() + " to " + file.getAbsolutePath());
    }
}

I tested this with multiple conditions, including a line that doesn't exist, a line at the end and a line with fewer lines left than the number to skip. 我用多个条件对它进行了测试,包括一条不存在的行,一条末尾的行和一条线路,其中剩下的行数比要跳过的数量少。 All worked and gave the appropriate results. 一切都奏效并给出了适当的结果。

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

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