I'm trying to write to a file using Java Streams. To my knowledge you don't have to catch an exception as long as you throw it forward. The compiler however throws an error (on the line of the stream.foreach()...) and says
error: unreported exception IOException; must be caught or declared to be thrown
Could someone explain why this is? (I'm only interested in solutions using streams)
public void save(String file, ArrayList<String> text) throws IOException {
FileWriter fw = new FileWriter(file);
text.stream().forEach(x->fw.write(x +"\n"));
fw.close();
}
Netbeans suggests this, but is there a shorter way?
public void save(String file, ArrayList<String> text) throws IOException {
FileWriter fw = new FileWriter(file);
text.stream().forEach(x->{
try {
fw.write(x +"\n");
} catch (IOException ex) {
...
}
});
fw.close();
}