我尝试过在网上寻找解决方案,但是只有知道了整条线,我才能找到解决问题的方法。
BufferedReader bufferedReader = new BufferedReader(new
FileReader("Hello.txt"));
String currentLine;
while((currentLine = bufferedReader.readLine()) != null){
if(currentLine.contains("are")){
//Delete the whole line.
}
}
预期结果:删除包含单词的行。 错误:无。
答案 0 :(得分:0)
这是我要做的方式。将要保留的行存储在列表中。然后只需将该列表重写到文件中即可。
// 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 );
}