我正在使用java 8流,並且我不能在流的foreach中拋出異常。在java 8流foreach中拋出異常
stream.forEach(m -> {
try {
if (isInitial) {
isInitial = false;
String outputName = new SimpleDateFormat(Constants.HMDBConstants.HMDB_SDF_FILE_NAME).format(new Date());
if (location.endsWith(Constants.LOCATION_SEPARATOR)) {
savedPath = location + outputName;
} else {
savedPath = location + Constants.LOCATION_SEPARATOR + outputName;
}
File output = new File(savedPath);
FileWriter fileWriter = null;
fileWriter = new FileWriter(output);
writer = new SDFWriter(fileWriter);
}
writer.write(m);
} catch (IOException e) {
throw new ChemIDException(e.getMessage(),e);
}
});
,這是我的異常類
public class ChemIDException extends Exception {
public ChemIDException(String message, Exception e) {
super(message, e);
}
}
我使用記錄器登錄上級的錯誤。所以我想拋出異常頂部。由於
從代碼我可以看到,它看起來像你應該使用'for'循環而不是流。您試圖在功能性環境中放置命令式代碼。 – 4castle
我想讀取大文件並將一些元素寫入另一個文件。這裏我正在做的是用過濾器讀取文件。所以我認爲最好的方法是使用流 –