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

时间:2015-05-19 12:57:39

标签: java string text-files

我有一些代码可以在文本文件中找到一个字符串,打印字符串所在的行,然后打印下面的5行。但是,我需要对其进行修改,以便在找到字符串后删除/删除行而不是打印。我该怎么做呢?

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) {
}

3 个答案:

答案 0 :(得分:3)

找一个你可以开始的小片段。

假设您的question.txt有以下输入。

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

此代码段将打印所有行并跳过行line 3 (1)以及之后的五行。

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

<强>输出

line 1
line 2
line 9
line 10

将行存储到文件中是为了您。

答案 1 :(得分:1)

我的建议是,您首先在上述代码之前声明并初始化StringBuilderoutput,如:

StringBuilder output = new StringBuilder();

现在,在if循环结束前while语句结束后,将该行附加到output并在最后添加"\n",如下所示:

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

现在终于在您发布的代码之后创建FileWriterwriter,然后使用编写器编写output,如下所示:

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

如果您不想在输出中打印它们,也不要忘记删除或注释掉以下行。

System.out.println(line);

答案 2 :(得分:0)

SubOtimal有一个很好的,简洁的答案,适用于大多数情况。以下更复杂但避免将整个文件加载到内存中。这对你来说可能不是问题,但以防万一...

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

我测试了多个条件,包括一条不存在的线,一条线在末尾,一条线的线数比要跳过的线数少。一切都奏效并给出了适当的结果。