package mypackage; /** * Utility class for reading (doubles) and writing to files. * * @author Jenny Orr * @version Fall2015 */ import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class FileIO { public FileIO() { } /** * Reads doubles (one per line) from a file . * * @param fileName the name of the file to be read (list of doubles, one per * line) * @return an array containing the data */ public static double[] readFile(String fileName) { double[] data = null; File file = new File(fileName); System.out.println("Reading data file: " + file.getAbsolutePath()); try { ArrayList dataList = new ArrayList(); Scanner reader = new Scanner(file); while (reader.hasNext()) { String d = reader.nextLine(); double temp = Double.parseDouble(d); dataList.add(temp); } reader.close(); data = new double[dataList.size()]; System.out.println("Length of array: " + dataList.size()); for (int i = 0; i < dataList.size(); i++) { data[i] = dataList.get(i); } } catch (FileNotFoundException e) { System.out.println(e + "\nFile not found:\n " + file.getAbsolutePath()); System.exit(0); } catch (NullPointerException e) { System.out.println("No data found " + e); System.exit(0); } catch (NumberFormatException e) { System.out.println("String does not contain a number. " + e); System.exit(0); } catch (Exception e) { System.out.println("Problem reading file. " + e); System.exit(0); } System.out.println("Done reading file."); return data; } /** * Returns a PrintWriter object for a file to be named fileName. If the file * already exists, returns null. * * @param fileName the name of the file to write to * @param overwrite if true will overwrite an existing file of same name. * @return a PrintWriter object or null if the file already exists. */ public static PrintWriter getPrintWriter(String fileName, boolean overwrite) { PrintWriter outputFile = null; try { File file = new File(fileName); if (!overwrite && file.exists()) { System.out.println("File already exists. Will not overwrite."); } else { if (file.exists()) { System.out.println("Overwriting file " + file.getAbsolutePath()); } else { System.out.println("Writing to " + file.getAbsolutePath()); } outputFile = new PrintWriter(file); return outputFile; } } catch (Exception e) { System.out.println(e + "\nProblem writing to file. " + fileName); System.exit(0); } return null; // file already exists so return null } }