120 likes | 197 Views
September 9, 2008. Lecture 5 – More IO. Alternatives . Given: FileReader myFreader; One way myFreader = new FileReader(“MyFile.txt”); Another way String fileName; fileName = “MyFile.txt”; myFreader = new FileReader(fileName);. Alternatives. Scanner fileScanner;
E N D
September 9, 2008 Lecture 5 – More IO
Alternatives Given: FileReader myFreader; One way myFreader = new FileReader(“MyFile.txt”); Another way String fileName; fileName = “MyFile.txt”; myFreader = new FileReader(fileName);
Alternatives • Scanner fileScanner; • fileScanner = new Scanner (new File (“a.txt”));
Alternatives • Scanner fileScanner; • String fileName; • fileName = “a.txt”; • fileScanner = new Scanner (new File (fileName));
Alternatives • Scanner fileScanner; • File myFile; • String fileName; • fileName = “a.txt” // get from user • myFile = new File (fileName); • fileScanner = new Scanner (myFile);
Alternatives • FileWriter fwriter; • fwriter = new FileWriter (“b.txt”); FileWriter fwriter; String fileName; fileName = “b.txt”; Fwriter = new FileWriter (fileName);
Alternatives PrintWriter myPrinter; myPrinter = new PrintWriter (new FileWriter (“b.txt”));
Example import java.util.Scanner;public class Test{ public static void main (String args []) { int number; Scanner keyboard; keyboard = new Scanner (System.in); System.out.println (" Hello "); System.out.println (" Please enter an integer and hit return "); while ( keyboard.hasNext()) { number = keyboard.nextInt (); System.out.println (" You entered " + number); } System.out.println (" Goodbye "); }}
Windows Screen Shot • U:\Web\CS239\Lectures\Lecture5>java Test • Hello • Please enter an integer and hit return • 65 • You entered 65 • 32 • You entered 32 • -235 • You entered -235 • ^Z • Goodbye • U:\Web\CS239\Lectures\Lecture5>java Test • Hello • Please enter an integer and hit return • 65 • You entered 65 • 32 • You entered 32 • ^D • Exception in thread "main" java.util.InputMismatchException • at java.util.Scanner.throwFor(Unknown Source) • at java.util.Scanner.next(Unknown Source) • at java.util.Scanner.nextInt(Unknown Source) • at java.util.Scanner.nextInt(Unknown Source) • at Test.main(Test.java:14) • U:\Web\CS239\Lectures\Lecture5>java Test • Hello • Please enter an integer and hit return • 53 • You entered 53 • 32 • You entered 32 • Goodbye • U:\Web\CS239\Lectures\Lecture5>
Alternatives PrintWriter myPrinter; FileWriter myWriter; myWriter = new FileWriter (“b.txt”); myPrinter = new PrintWriter (myWriter);
Alternatives PrintWriter myPrinter; FileWriter myWriter; String fileName; fileName = “b.txt”; myWriter = new FileWriter (fileName); myPrinter = new PrintWriter (myWriter);
Alternatives • End of file character • Unix • <ctrl-d> • Windows • <ctrl-z>