1

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 ?

Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36
  • 3
    I suggest you use `PrintWriter.println` Note: Writer.write doesn't put a new line between outputs. – Peter Lawrey Apr 23 '15 at 14:16
  • 2
    Why don't you simply use something like `Files.copy(Paths.get("originalFile"), Paths.get("outputFile1.txt"));`? – Alexis C. Apr 23 '15 at 14:19
  • 1
    How about providing lambda which will handle this exception http://stackoverflow.com/a/14045585/1393766 http://stackoverflow.com/questions/18198176/java-8-lambda-function-that-throws-exception? – Pshemo Apr 23 '15 at 14:44
  • 1
    What about `fileData.forEach(l -> write(writer, l);` where this::write is method `public void write(BufferedWriter writer, String line)` and you handle exception there with try-catch. But that is not perfect while if exception is thrown, in most case you can't write to file anymore, so you will just fast forward through rest of lines – Lukino Apr 23 '15 at 14:58
  • @Shirish I can't test this since I don't currently have Java but this might assist you: http://java.dzone.com/articles/java-8-stream-and-lambda basically takes each string in the stream and writes to a file. – matrixanomaly Apr 23 '15 at 15:00
  • A Consumer doesn't throw IOException. But BufferedWriter.write() does. So writer::write can't be a Consumer. – JB Nizet Apr 23 '15 at 15:30
  • 2
    http://stackoverflow.com/a/28617603/1441122 – Stuart Marks Apr 23 '15 at 16:56
  • thanks all for your responses...I wil try the Printwriter.write(). – Shirishkumar Bari Apr 23 '15 at 17:16

0 Answers0