在此代码中,使用一个文件(new.txt)完成一些操作
我想将下面代码的输出存储在另一个文件中….
public static void main(String a[]) throws Exception {
try {
Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
.replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
.split("1003.*?1002")) // split on end-to-start-of-next
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
解决方法:
由于您已将整个文件内容保留在内存中,因此非流解决方案更直接.
String txt = new String(Files.readAllBytes(Paths.get("in.txt")), StandardCharsets.UTF_8);
txt = txt.replaceAll(...);
txt = txt.replaceAll(...); // split behavior
Files.write(Paths.get("out.txt"), txt.getBytes(StandardCharsets.UTF_8));
添加:
虽然逻辑逃脱了我,但替换可能应该是:
finale String EOL = "\n";
txt = txt.replaceAll("^.*?1002|1003(.(?!1002))*$", EOL ) // trim leading/trailing non-data
txt = txt.replaceAll("1003.*?1002", EOL ) // split on end-to-start-of-next