Therefore, when I hear someone mention that he wants to filter the text, I immediately think about going to Streams (mainly because there is a method called filter that filters exactly as you need). Another answer mentions using Stream with the Apache commons-io library, but I thought it would be wise to show how this can be done in standard Java 8. Here is the simplest form:
public void removeLine(String lineContent) throws IOException { File file = new File("myFile.txt"); List<String> out = Files.lines(file.toPath()) .filter(line -> !line.contains(lineContent)) .collect(Collectors.toList()); Files.write(file.toPath(), out, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
I think that there is not much to explain, basically Files.lines receives Stream<String> lines of the file, filter Files.lines lines that we don’t need, and then collect puts all the lines of the new file in the List . Then we write the list on top of the existing file using Files.write , using the optional TRUNCATE option to replace the old contents of the file.
Of course, this approach has a flip side: loading each line into memory, since they are all stored in a List before being written back. If we wanted to just change without saving, we would need to use some form of OutputStream to write each new line to the file when it passes through the stream, for example:
public void removeLine(String lineContent) throws IOException { File file = new File("myFile.txt"); File temp = new File("_temp_"); PrintWriter out = new PrintWriter(new FileWriter(temp)); Files.lines(file.toPath()) .filter(line -> !line.contains(lineContent)) .forEach(out::println); out.flush(); out.close(); temp.renameTo(file); }
In this example, little has changed. In fact, instead of using the collect command to collect the contents of the file into memory, we use forEach so that each line passing through the filter sent to PrintWriter for immediate writing to the file and not saved. We must save it to a temporary file because we cannot overwrite the existing file at the same time that we are still reading from it, so at the end we rename the temporary file to replace the existing file.
Tim M. Aug 20 '17 at 16:06 on 2017-08-20 16:06
source share