totalngrams: detect early if output file can be written
diff --git a/src/main/java/org/ids_mannheim/TotalNGram.java b/src/main/java/org/ids_mannheim/TotalNGram.java
index 949d7ab..992b03c 100644
--- a/src/main/java/org/ids_mannheim/TotalNGram.java
+++ b/src/main/java/org/ids_mannheim/TotalNGram.java
@@ -1,16 +1,19 @@
package org.ids_mannheim;
+import picocli.CommandLine;
+
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.PrintStream;
+import java.nio.file.AccessDeniedException;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import picocli.CommandLine;
-
@CommandLine.Command(mixinStandardHelpOptions = true,
name = "totalngram", description = "add ngram counts from KorAP-XML or CoNLL-U files")
@@ -24,8 +27,12 @@
@SuppressWarnings("CanBeFinal")
@CommandLine.Option(names = {"-o",
- "--output-file"}, description = "Output file (default: -")
- File output_file = null;
+ "--output-file"}, description = "Output file (default: ${DEFAULT-VALUE})")
+ String output_fillename = "-";
+
+ @SuppressWarnings("CanBeFinal")
+ @CommandLine.Option(names = {"--force"}, description = "Force overwrrite (default: ${DEFAULT-VALUE})")
+ boolean force_overwrite = false;
@SuppressWarnings("CanBeFinal")
@CommandLine.Option(names = {"-P",
@@ -50,7 +57,24 @@
@Override
public Integer call() throws Exception {
- PrintStream output_stream = (output_file == null || output_file.equals("-") ? System.out : new PrintStream(output_file));
+ PrintStream output_stream;
+ if ((output_fillename == null) || output_fillename.equals("-")) {
+ output_stream = System.out;
+ } else {
+ File f = new File(output_fillename);
+ try {
+ Files.createFile(f.toPath());
+ } catch (AccessDeniedException e) {
+ System.err.println("ERROR: Cannot write output file '" + output_fillename + "'");
+ System.exit(-1);
+ } catch (FileAlreadyExistsException e) {
+ if (!force_overwrite) {
+ System.err.println("ERROR: '" + output_fillename + "' already exits. Use --force to overwrite.");
+ System.exit(-1);
+ }
+ }
+ output_stream = new PrintStream(f);
+ }
FoldedEntry.setFolds(FOLDS);
ConcurrentHashMap<String, FoldedEntry> map = new ConcurrentHashMap<>();
@@ -83,7 +107,7 @@
return null;
}
- public static void main(String[] args) throws FileNotFoundException {
+ public static void main(String[] args) {
System.exit(new CommandLine(new TotalNGram()).execute(args));
}
}