Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC1401 Input and Output (with Files)

Similar presentations


Presentation on theme: "CSC1401 Input and Output (with Files)"— Presentation transcript:

1 CSC1401 Input and Output (with Files)

2 Learning Goals Computing concepts Input and output with files in Java
Using the Scanner class for file input, and PrintWriter for output

3 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();

4 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

5 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(); …

6 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

7 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

8 File Output Again, we’ll change from System.out to something else

9 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();

10 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

11 Reading Assignment Media Computation Chapter 12, Section 3 (but not section )


Download ppt "CSC1401 Input and Output (with Files)"

Similar presentations


Ads by Google