在Java中,我有一个文件,其中包含以下行:
abc
cbd
CFG
...
如果任何行与字符串匹配,我想从文件中删除CFG,这可能是'cfg','Cfg'或其他不区分大小写的变体。
如果我将文件读入Set,如何实现此目的?通过将文件读入列表似乎更可行。
以下是所需代码的“ lambda版本”。感谢@Sam提供有关重新引发任何被抑制的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");
}
}
如果您需要就地修改文件,则在读取文件时对其进行写入会更加困难。您可以先将其全部读入内存。
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");
}
}
最后,以防万一,是一种与Java 7兼容的非lambda解决方案:
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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句