Другое решение, вместо того, чтобы есть IOException
(антипаттерн), преобразовать его в соответствующий подкласс RuntimeException
и выбросить из блока catch.
Кроме того, в вашем примере вы пропускаете файлобработчик, не закрывая FileWriter
в исключительной ситуации.
public Path writeToFile() {
final Path tempFilePath;
try {
tempFilePath = Files.createTempFile(Paths.get(""), "sorting_test_", ".txt");
} catch (IOException e ) {
throw new MyRuntimeException(
"Cannot create sorting_test temp file",
e
);
}
try (final FileWriter fw = new FileWriter(tempFilePath.toFile())) {
try(final BufferedWriter bw = new BufferedWriter(fw)) {
for (List<Integer> arr : arrays) {
// Convert array ints to strings, join it to single string and write
bw.write(arr.stream()
.map(String::valueOf)
.collect(Collectors.joining(" ")));
bw.newLine();
}
}
return tempFilePath;
} catch (IOException e) {
throw new MyRuntimeException(
"Cannot write to " + tempFilePath,
e
);
}
}