Java流API:修改文件中的特定行



我正在读取readme文件的内容作为字符串列表

我想修改这个文件的特定行(也就是列表的特定字符串)。

我设法实现了它,但是有一个优雅的方法来做到这一点(只有)java流操作(因为我目前正在学习java流API)?

我发现的其他代码显示了如何创建一个新列表,并在执行replaceAll()或附加某些字符后向该列表添加新字符串。

我的情况有点不同,我想只改变我在文件中找到的某一行(更具体地说,它的某些字符,即使我很好地重写整行)。现在,我只是在一个新列表中一个接一个地重写所有行,除了我生成并写入的一行(也就是我想要修改的行)。

我是开放的任何方式这样做,我可以改变I/o类型,重写整个文件/行或只是改变它的一部分…只要我最终修改了readme文件。只是在寻找一条"小溪">

我的实际代码:

private static List<String> getReadme() {
try {
return stream(readFileToString(new File("readme.md")).split("n")).collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void generateReadMe(String day, String year, int part) {
List<String> readme = getReadme();
// hidden code where I create the line I want to end up modified...
String line = prefix + fDay + stars + color + packages + fYear + "/days/Day"+ day +".java)n";
List<String> newReadme = readme.stream().map(l -> {
if (l.contains(fYear) && l.contains(fDay)) {
// add the modified line (aka replacing the line)
return line;
} else {
// or add the non modified line if not the one we're looking for
return l;
}
}).toList();
newReadme.forEach(System.out::println);
}

你不需要Apache commons,我建议使用Files.linesjava.nio.file.Files,你也可以像下面这样实现一个单一的方法

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example {
public static void generateReadMe(String day, String year, int part) {
List<String> newReadme = null;
try (Stream<String> lines = Files.lines(Paths.get("readme.md"))) {
newReadme = lines.map(l -> l.contains(fYear) && l.contains(fDay) ? replaceLine() : l).collect(Collectors.toList())
} catch (IOException e) {
throw new RuntimeException(e);
}
newReadme.forEach(System.out::println);
}
private static String replaceLine() {
//Your implementation
return prefix + fDay + stars + color + packages + fYear + "/days/Day" + day + ".java)n";
}
}

最新更新