CSC1401 Input and Output (with Files)
Learning Goals Computing concepts Input and output with files in Java Using the Scanner class for file input, and PrintWriter for output
Recall … import java.util.*; // needed for scanner class IOTesting { public static void main(String [] args) { Scanner scan = new Scanner(System.in); int value = scan.nextInt(); …
Using Files for input Instead of System.in, we can specify a file Two differences We need to import java.io.*; Doing file input can lead to an exception if the type of data we are requesting doesn’t match what’s in the file
Note the changes import java.util.*; // needed for scanner import java.io.*; // needed for file class FileIO { public static void main(String [] args) throws Exception // throws exception is for file i/o { Scanner sc = new Scanner(System.in); Scanner sc2 = new Scanner(new File("data.txt")); int i = sc2.nextInt(); …
Let’s create a file and try Can use Notepad, or just about anything else besides MS Word Let’s read in a bunch of scores into an array
Reading several numbers from a file Scanner sc2 = new Scanner(new File("data.txt")); int [] list = new int[10]; int count = 0; while (sc2.hasNextInt() && count < 10) { list[count] = sc2.nextInt(); count = count +1; } for (int i = 0; i< count;i++) { System.out.println("list[“ + i + "] = “ + list[i]); } sc2.close(); // when you open a file, you // should close it
File Output Again, we’ll change from System.out to something else
An example with file output import java.io.*; // needed for file class IO { public static void main(String [] args) throws Exception // throws exception is for file i/o { int i = 5; PrintWriter steveout = new PrintWriter( new FileWriter("silly2.txt")); steveout.println(i+ " is the value"); steveout.close(); …
Summary We use Printwriter for output to a file (the Media Computation book has an alternate approach) We use a Scanner object for getting input from a file
Reading Assignment Media Computation Chapter 12, Section 3 (but not section 12.3.3)