package oligo3; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; /**Types and method for safely opening an output file for writing lines of text. * Note: Don't forget to close the BufferedWriter stream after using this class. */ public class OutputFile { public static File f; private static FileWriter fw; public static PrintWriter pw; public static PrintWriter genes; public static PrintWriter overlaps; public static PrintWriter stats; public static PrintWriter tags; /**Check and open file and create FileWriter and BufferedWriter. * @param String filename contains no the path to the file to be opened. */ public static boolean WriteOkay(String dir, String filename, boolean append) throws FileNotFoundException, IOException { //FileWriter always assumes that default encoding is Okay! f = new File(dir, filename); if (f == null) { throw new IllegalArgumentException("File should not be null."); } else if (!f.exists()) { System.out.println("\n" + f.getName() + ": File does not exist."); if (f.createNewFile()) { System.out.println("Successfully created the file: " + f.getName()); } else { System.out.println("Unable to create the file " + f.getName()); } } // Check the existing or freshly created file if (!f.isFile()) { throw new IllegalArgumentException(f + ": Is a directory, not a file."); } else if (!f.canWrite()) { throw new IllegalArgumentException(f + ": File cannot be written."); } // Continue checking try { fw = new FileWriter(f, append); pw = new PrintWriter(fw); } catch (IOException e) { System.err.println("I/O File Write Error: " + e.getMessage()); System.exit(1); } catch (Exception e) { System.err.println("Print Write Error: " + e.getMessage()); System.exit(1); } return f.canWrite(); } public static void createOutFiles() throws IOException { // Use overwrite mode to clear existing file contents. if (WriteOkay(Params.output_files_dir, Params.output_genes_file, false)) pw.close(); if (WriteOkay(Params.output_files_dir, Params.out_overlaps_file, false)) pw.close(); if (WriteOkay(Params.output_files_dir, Params.ORF_stats_file, false)) pw.close(); if (WriteOkay(Params.output_files_dir, Params.ORF_tags_file, false)) pw.close(); // Stay append mode after clearing existing file contents. if (WriteOkay(Params.output_files_dir, Params.output_genes_file, true)) genes = pw; if (WriteOkay(Params.output_files_dir, Params.out_overlaps_file, true)) overlaps = pw; if (WriteOkay(Params.output_files_dir, Params.ORF_stats_file, true)) stats = pw; if (WriteOkay(Params.output_files_dir, Params.ORF_tags_file, true)) tags = pw; } }