// IOTool.java // // Author: Rahul Simha // Summer 2017 // // A tool that hides the ugly details of screen and file IO // for initial use. We'll later expose the detail. import java.util.*; import java.io.*; public class IOTool { public static String readStringFromTerminal (String prompt) { System.out.print (prompt); Scanner console = new Scanner (System.in); String s = console.nextLine (); return s; } public static int readIntFromTerminal (String prompt) { System.out.print (prompt); Scanner console = new Scanner (System.in); int i = console.nextInt (); return i; } public static double readDoubleFromTerminal (String prompt) { System.out.print (prompt); Scanner console = new Scanner (System.in); double d = console.nextDouble (); return d; } public static String[] readTextFileAsStringArray (String filename) { ArrayList lines = readTextFileAsStringList (filename); // Convert to array. String[] lineArray = (String[]) lines.toArray (); return lineArray; } public static ArrayList readTextFileAsStringList (String filename) { try { File f = new File (filename); if (! f.exists()) { System.out.println ("No such file: " + filename); return null; } LineNumberReader lnr = new LineNumberReader (new FileReader(f)); ArrayList lines = new ArrayList (); String line = lnr.readLine (); while (line != null) { lines.add (line); line = lnr.readLine (); } return lines; } catch (Exception e) { System.out.println (e); e.printStackTrace (); System.exit (0); } return null; } public static void writeTextFileFromStringArray (String filename, String[] lines) { try { PrintWriter pw = new PrintWriter (new FileWriter (filename)); for (String s: lines) { pw.println (s); } pw.flush (); pw.close (); } catch (Exception e) { System.out.println (e); e.printStackTrace (); System.exit (0); } } public static int stringToInt (String s) { try { // Remove surrounding whitepace. s = s.trim (); // Parse. int k = Integer.parseInt (s); return k; } catch (Exception e) { // If the string was illegal, our action is harsh: halt. System.out.println ("Illegal string for integer: " + s); System.exit (0); // We won't be reaching here but the compiler needs a // return to be written. return -1; } } }