The following is a "lambda version" of the required code. Thanks to @Sam for the important point about re-raising any suppressed PrintWriter IOException.
Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (PrintWriter pw = new PrintWriter(out_file.toFile())) {
Files.lines(in_file)
.filter(line -> !line.equalsIgnoreCase("cfg"))
.forEach(pw::println);
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}
If you need to modify the file in place, then writing to it while reading from it is somewhat more difficult. You could read it all into memory first.
Path path = new Path("filename");
List<String> lines = Files.lines(path)
.filter(line -> !line.equalsIgnoreCase("cfg"))
.collect(Collectors.toList());
try(PrintWriter pw = new PrintWriter(path.toFile())) {
lines.forEach(pw::println);
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}
And finally, just in case, a non-lambda solution for compatibility with Java 7:
Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (BufferReader reader = Files.newBufferedReader(in_file);
PrintWriter pw = new PrintWriter(out_file.toFile())) {
String line;
while((line = reader.readline()) != null) {
if (!line.equalsIgnoreCase("cfg")) {
pw.println(line);
}
}
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}