I am fascinated with the features that stream api provides in Java8.
I tried to write file using stream but it gives an exception. I want a way to handle this exception. I know PrintWriter
has a write()
method which does not throws an exception. I was trying to know the strategy as to how to pass in methods that can throw exception. possibly by writing our own custom exception handler ? I am working on this , I will share once it complete.
Method to write data
private static void writeDataToSecondFileWithJavaStreams(File inputFile) throws IOException {
Stream<String> fileData = Files.lines(Paths.get(inputFile.getParent(), inputFile.getName()));
File outputFile = new File(inputFile.getParent(),"outputFile1.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
// fileData.parallel();
// fileData.forEach(System.out::println); // this works perfectly fine
fileData.forEach(writer::write);
writer.close();
System.out.println("File writing completed");
}
whereas fileData.forEach(System.out::println)
works perfectly fine but I dont want to write data to console rather to an output file.
I am getting error UnHandled IOException at fileData.forEach(writer::write);
this line. I know its because forEach expects a lambda function that does not throws any exceptions .
Suggestions on how to make it work ?