Skip to content

Commit

Permalink
be a bit smarter about parent directory creation in csv writer
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolaspayette committed Nov 8, 2024
1 parent 9cb04bc commit 9e59191
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions io/src/main/java/uk/ac/ox/poseidon/io/CsvParserUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,11 @@
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.nio.charset.StandardCharsets.UTF_8;

Expand Down Expand Up @@ -160,8 +158,7 @@ public static <C extends Collection<?>> void writeRows(
final Collection<?> headers,
final Iterable<C> rows
) {
// noinspection ResultOfMethodCallIgnored
outputFile.getParent().toFile().mkdirs();
createOutputFolderIfNeeded(outputFile);
try (final OutputStream outputstream = Files.newOutputStream(outputFile)) {
final CsvWriterSettings csvWriterSettings = new CsvWriterSettings();
final CsvWriter csvWriter = new CsvWriter(outputstream, csvWriterSettings);
Expand All @@ -171,4 +168,17 @@ public static <C extends Collection<?>> void writeRows(
throw new RuntimeException(e);
}
}

private static void createOutputFolderIfNeeded(final Path outputFile) {
Optional
.ofNullable(checkNotNull(outputFile).toAbsolutePath().getParent())
.map(Path::toFile)
.filter(parentFolder -> !parentFolder.exists())
.ifPresent(parentFolder -> {
final boolean created = parentFolder.mkdirs();
if (!created) {
throw new RuntimeException("Failed to create output folder: " + parentFolder);
}
});
}
}

0 comments on commit 9e59191

Please sign in to comment.