假设我有一句话:“你好,杰森,你今天好吗?”在文本文件内。 假设我不知道那一行是什么,但我有一个字符串,例如“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/