/* * FileAndConsoleTester shows elementary examples of how to do I/O * using text files and the console. * * Written: February 2002 * * @author Jeff Ondich */ import java.io.*; class FileAndConsoleTester { public static void fileOutputTest() throws IOException { File outFile = new File( "C:/Windows/Desktop/outputfile.txt" ); PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter(outFile)) ); out.print( "Hello " ); out.println( "world" ); out.close(); } public static void fileInputTest() throws IOException { File inFile = new File( "C:/Windows/Desktop/words.txt" ); BufferedReader in = new BufferedReader( new FileReader(inFile) ); while( in.ready() ) { String s = in.readLine(); System.out.println( s.toUpperCase() ); } in.close(); } public static void consoleRead() throws IOException, NumberFormatException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in) ); System.out.print( "What's your name? " ); String name = in.readLine(); System.out.print( "What's your favorite number? " ); String favoriteNumber = in.readLine(); System.out.println( name + "'s favorite number is " + favoriteNumber + "." ); double x = Double.parseDouble( favoriteNumber ); double rootX = Math.sqrt( x ); System.out.println( "The square root of " + name + "'s number is " + rootX ); } public static void consoleRead2() throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in) ); System.out.print( "What's your name? " ); String name = in.readLine(); System.out.print( "What's your favorite number? " ); String favoriteNumber = in.readLine(); System.out.println( name + "'s favorite number is " + favoriteNumber + "." ); double x = 0; try { x = Double.parseDouble( favoriteNumber ); } catch( NumberFormatException e ) { System.out.println( favoriteNumber + " isn't really a number, now is it?" ); } double rootX = Math.sqrt( x ); System.out.println( "The square root of " + name + "'s number is " + rootX ); } }