我试图用以下代码中的流替换普通的 for 循环,该循环在 Writer 对象中写入字符串值:
public void save() {
try (Writer fileWriter = new FileWriter(file)) {
fileWriter.write("someStrings\n");
ArrayList<ParentType> parentList = super.getParentType();
for (ParentType parentTypeObj : parentList) {
fileWriter.write(toString(parentTypeObj) + "\n");
}
ArrayList<ChildType> childList = super.getChildType();
for (ChildType childTypeObj : childList) {
fileWriter.write(toString(childTypeObj) + "\n");
}
} catch (IOException e) {
throw new ManagerSaveException();
}
}
如何做?
期望通过流在 Writer 对象中写入字符串值。
基本上应该看起来像(
childList
相同):
ArrayList<ParentType> parentList = super.getParentType();
parentList.stream() // Stream<ParentType>
.map(p -> p.toString()+"\n") // Stream<String>
.forEach(fileWriter::write);
唉,
write
方法可能会抛出异常,而Stream
API 禁止这样做。然后你必须:
write
方法封装在内部管理异常的方法中。 .forEach(s -> {
try {
fileWrite.write(s);
} catch(Exception e) {
// internally catched
}
})
Stream
之外。 .forEach(s -> {
try {
fileWrite.write(s);
} catch(Exception e) {
throw new RuntimeException("Bang!",e); // so that it can be catched outside the Stream by chaining it to a RuntimeException.
}
})