totalngrams: factor out file creation
diff --git a/src/main/java/org/ids_mannheim/TotalNGram.java b/src/main/java/org/ids_mannheim/TotalNGram.java
index 2774da4..fb0ea3e 100644
--- a/src/main/java/org/ids_mannheim/TotalNGram.java
+++ b/src/main/java/org/ids_mannheim/TotalNGram.java
@@ -105,18 +105,7 @@
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);
- }
- }
+ File f = Utils.createFile(output_fillename, force_overwrite);
if (output_fillename.endsWith(".gz")) {
output_stream = new PrintStream(new ParallelGZIPOutputStream((new BufferedOutputStream(new FileOutputStream(f)))));
} else {
diff --git a/src/main/java/org/ids_mannheim/Utils.java b/src/main/java/org/ids_mannheim/Utils.java
index 7d60dc9..3ac2966 100644
--- a/src/main/java/org/ids_mannheim/Utils.java
+++ b/src/main/java/org/ids_mannheim/Utils.java
@@ -1,10 +1,42 @@
package org.ids_mannheim;
+import java.io.File;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+import java.nio.file.AccessDeniedException;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Files;
+
public class Utils {
public static String newExtension(String original, String newExtension) {
+ if(original.equals("-"))
+ throw new IllegalArgumentException("Cannot add a file name extension to stdout.");
if (original.contains("."))
return original.replaceFirst("(\\.[^.]*|\\.[^.]+\\.gz)$", "."+newExtension);
else
return original+".log";
}
+
+ public static File createFile(String fname, boolean force_overwrite) {
+ File f = new File(fname);
+ try {
+ Files.createFile(f.toPath());
+ } catch (AccessDeniedException e) {
+ final String message = "ERROR: Cannot write file '" + fname + "'";
+ System.err.println(message);
+ TotalNGram.logger.severe(message);
+ System.exit(-1);
+ } catch (FileAlreadyExistsException e) {
+ if (!force_overwrite) {
+ final String message = "ERROR: '" + fname + "' already exits. Use --force to overwrite";
+ TotalNGram.logger.severe(message);
+ System.err.println(message);
+ System.exit(-1);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return f;
+ }
}
+