java - 从文件中读取一行的一部分然后将其删除

标签 java delete-row

假设我有一句话:“你好,杰森,你今天好吗?”在文本文件内。 假设我不知道那一行是什么,但我有一个字符串,例如“are”,并且单词“are”仅显示在该文本内的该行中。 在不知道同一行中的其他单词的情况下,我如何才能找到这个地方并删除整行?

我尝试过在网上寻找解决方案,但只有在了解整条信息的情况下才能找到问题的解决方案。

BufferedReader bufferedReader = new BufferedReader(new 
FileReader("Hello.txt"));
String currentLine;
    while((currentLine = bufferedReader.readLine()) != null){
        if(currentLine.contains("are")){
        //Delete the whole line.
        }
}

预期结果:删除包含单词的行。 错误:无。

最佳答案

这是我的做法。将您想要保留的行存储在列表中。然后只需将该列表重写到文件中即可。

// using for loop
private static void option1( final File FILE ) throws IOException {

    // read all lines from file into a list
    List<String> fileContent = new ArrayList<>( Files.readAllLines( FILE.toPath(), StandardCharsets.UTF_8 ) );

    List<String> linesToWrite = new ArrayList<>(); // new list of lines that we want to keep
    for ( String line : fileContent ) {

        if ( !line.contains( "are" ) ) {
            // line doesn't contain are, so add to our list of lines to keep
            linesToWrite.add( line );
        }

    }

    // write the lines we want back to the file
    Files.write( FILE.toPath(), linesToWrite, StandardCharsets.UTF_8 );
}

// using Java 8 Streams
private static void option2( final File FILE ) throws IOException {

    // read all lines from file into a list
    List<String> fileContent = new ArrayList<>( Files.readAllLines( FILE.toPath(), StandardCharsets.UTF_8 ) );

    // filter using streams
    fileContent = fileContent.stream()
            .filter( line -> !line.contains( "are" ) ) // filter out all lines that contain are
            .collect( Collectors.toList() );

    // write the lines we want back to the file
    Files.write( FILE.toPath(), fileContent, StandardCharsets.UTF_8 );
}

关于java - 从文件中读取一行的一部分然后将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976366/

相关文章:

ios - UITableView:未调用 "didDeselectCell"方法,尽管单元格被取消选择

java - token "super"语法错误,名称无效

java - 如何在java中用selenium获取包裹在段落元素<p>中的文本的值

应用程序启动时加载程序 dalvik.system.PathClassLoader 中的 java.lang.ClassNotFoundException

SQL从相关表中删除

python - 从 dataframe pandas python 中删除一个例子

java - SQL Server 短暂登录失败 "Cannot open database "**** *"requested by the login. The login failed."

java - 谁能知道如何使用 android 在 facebook 上发布照片作为评论?

c - 如何使用C编程语言删除文本文件中的特定行

delete-row - 从 InfluxDB 测量中删除具有不需要的字段值的点