Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在文本文件中查找字符串,删除下面的行和行_Java_String_Text Files - Fatal编程技术网

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

Java 在文本文件中查找字符串,删除下面的行和行,java,string,text-files,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 (lin

我有一些代码可以在文本文件中查找字符串,打印字符串所在的行,然后打印下面的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) {
}
File File=new文件(“./output.txt”);
扫描仪输入=空;
试一试{
in=新扫描仪(文件);
while(在.hasNext()中){
String line=in.nextLine();
如果(第行包含(“(1)”){
对于(int a=0;in.hasNextLine()&&a<6;a++){
系统输出打印项次(行);
line=in.nextLine();
}
}
}
}捕获(例外e){
}

找到一个小片段,您可以从中开始

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

line 1
line 2
line 3 (1)
line 4
line 5
line 6
line 7
line 8
line 9
line 10
此代码段将打印所有行,并跳过第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));
}

将行存储到文件中的操作留给您。

我的建议是,您首先声明并初始化一个
StringBuilder
say
output
,然后再执行上述代码,如:

StringBuilder output = new StringBuilder();
现在,在关闭
if
语句之后,在关闭
while
循环之前,将该行附加到
输出
,并在末尾添加一个
“\n”
,如下所示:

output.append(line+"\n");
现在,在发布代码之后,创建一个
文件编写器
编写器
,然后使用编写器编写
输出
,如下所示:

try(FileWriter writer = new FileWriter(file, false)){
   writer.write(output);
}catch IOException(e){
   e.printStackTrace();
}
如果您不想在输出中打印,也不要忘记删除或注释掉下面的行

System.out.println(line);

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

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());
    }
}
public void deleteAfter(文件文件、字符串搜索字符串、int-lineCountToDelete){
//创建要写入的临时文件
File temp=新文件(File.getAbsolutePath()+“.tmp”);
try(BufferedReader=newbufferedreader(newfilereader(file));
PrintWriter writer=新的PrintWriter(新文件编写器(临时))){
//读到我们要找的那一行
//并将每个文件写入临时文件
弦线;
而((line=reader.readLine())!=null&&!line.equals(searchString)){
writer.println(行);
}
//跳过要“删除”的行数
//同时也要注意文件的结尾
对于(int i=0;i

我在多个条件下对此进行了测试,包括不存在的一行、末尾的一行以及剩余行数少于要跳过的行数的一行。所有操作都已完成,并给出了相应的结果。

是否要删除包含字符串的行之后的行或包含字符串的行之后的所有行?您的输入文件可能包含多少行?包括字符串和以下五行。创建一个
StringBuilder
并将所需的行附加到此对象,然后在
FileWriter
的帮助下覆盖该文件,作为旁注:当您在Unix系统上工作时。。。您可以简单地使用grep及其选项-A和-B来实现这一点:匹配模式并在模式之前/之后打印行。无需再次实施。。。几十年前已经实现了什么。如果字符串出现在两个不同的行中怎么办?
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());
    }
}