D
D
DarkByte20152017-06-02 20:29:11
Java
DarkByte2015, 2017-06-02 20:29:11

Why does it give a compilation error?

Please tell me why in this code:

public void write() throws IOException {
  String splitter = String.join("", Collections.nCopies(settings.page.width, "-"));
  List<String> headLines = columnsToRows(getColumnTitles());

  try (BufferedWriter writer = Files.newBufferedWriter(outputPath, DEFAULT_CHARSET)) {
      inputData.stream().map(this::columnsToRows).flatMap(List::stream).forEach(writer::write);
  }
}

Swears at the call forEach(writer::write) - "Unhandled exception: java.io.IOException"? After all, the method signature explicitly states that it throws this type of exception! I don't need to catch it here, I want it to fly out of the method if there is an exception (I catch it there).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DarkByte2015, 2017-06-02
@DarkByte2015

In short, I did this:

public void write() throws IOException {
  List<String> columnTitles = settings.columns.stream().map(x -> x.title).collect(Collectors.toList());
  String splitter = String.join("", Collections.nCopies(settings.page.width, "-"));
  List<String> headLines = columnsToRows(columnTitles);

  try (BufferedWriter writer = Files.newBufferedWriter(outputPath, DEFAULT_CHARSET)) {
      Stream<String> lines = inputData.stream().flatMap(x -> columnsToRows(x).stream().limit(columnTitles.size()));
      Iterator<String> iterator = lines.iterator();

      while (iterator.hasNext()) {
    String line = iterator.next();
    writer.write(line);
      }
  }
}

S
Shockoway, 2017-06-02
@Shockoway

Alternatively, you could throw an unchecked exception:

public void write() {
        String splitter = String.join("", Collections.nCopies(settings.page.width, "-"));
        List<String> headLines = columnsToRows(getColumnTitles());

        try (BufferedWriter writer = Files.newBufferedWriter(outputPath, DEFAULT_CHARSET)) {
            inputData.stream().map(this::columnsToRows).flatMap(List::stream).forEach(writer::write);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question