Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 110: Spring 20091 Announcements Program 5 Milestone 1 was due today Program 4 has been graded.

Similar presentations


Presentation on theme: "COMP 110: Spring 20091 Announcements Program 5 Milestone 1 was due today Program 4 has been graded."— Presentation transcript:

1 COMP 110: Spring 20091 Announcements Program 5 Milestone 1 was due today Program 4 has been graded

2 COMP 110: Spring 20092 Today in COMP 110 Review Exceptions Basic File I/O Programming Demo

3 COMP 110: Spring 20093 Review Exceptions

4 COMP 110: Spring 20094 Exceptions An exception is an object that signals the occurrence of an unusual (exceptional) event during program execution Exception handling is a way of detecting and dealing with these unusual cases in principled manner i.e. without a run-time error or program crash

5 COMP 110: Spring 20095 The try Block A try block contains the basic algorithm for when everything goes smoothly Try blocks will possibly throw an exception Syntax try { Code_To_Try } Example try { average = scoreSum/numGames; }

6 COMP 110: Spring 20096 The catch Block The catch block is used to deal with any exceptions that may occur This is your error handling code Syntax catch(Exception_Class_Name Catch_Block_Parameter) { Process_Exception_Of_Type_Exception_Class_Name } Possibly_Other_Catch_Blocks Example catch(ArithmeticException e) { System.out.println(e.getMessage()); System.out.println("Cannot compute average for 0 games"); }

7 COMP 110: Spring 20097 Example Using Exception Handling (try/catch blocks) int score = keyboard.nextInt(); int scoreSum = 0; int numGames = 0; while(score >= 0) { scoreSum += score; numGames++; score = keyboard.nextInt(); } double average = 0; try { average = scoreSum/numGames; } catch(ArithmeticException e) { System.out.println(e.getMessage()); System.out.println("Cannot compute average for 0 games"); }

8 COMP 110: Spring 20098 Files Your music, pictures, videos, even your Java programs are stored on your computer in files Files can also be used to store input for a program, or a program’s output

9 COMP 110: Spring 20099 Streams Writing to & reading from files is done using a stream A stream is a flow of data This data might be characters, numbers or bytes of binary digits Data that flows INTO your program is called an input stream Data that flows OUT of your program is called an output stream

10 COMP 110: Spring 200910 Streams Program Keyboard CD Input Stream Monitor Hard drive Output Stream

11 COMP 110: Spring 200911 Stream Class In Java, streams are objects of special stream class Scanner objects are input streams We’ve used the Scanner class to read data from the keyboard System.out is an output stream We use it to print data out to screen

12 COMP 110: Spring 200912 File I/O File I/O stands for File Input/Output Why use files for input/output? Permanent data storage Easy to read in large amount of data We can also read it in repeatedly Easy to output large amounts of data that can be analyzed later

13 COMP 110: Spring 200913 Text Files vs Binary Files All files are stored as binary digits (bits) In some cases this data is interpreted as text (text files) Your Java files Text files can be easily read/edited by humans All other files are binary files Your music & picture files Binary files cannot be easily read/edited by humans

14 COMP 110: Spring 200914 Creating a Text File The PrintWriter class is provided by Java to aid in creating and writing text files Need to import from java.io Before we can write to a text file, we need to connect to an output stream This is essentially opening the file, which allows us to write to it All files have a name, such as out.txt, that we use when opening the file

15 COMP 110: Spring 200915 Opening a Text File //need to import java.io.PrintWriter //& java.io.FileNotFoundException String fileName = "out.txt"; PrintWriter outputStream = null; try { outputStream = new PrintWriter(fileName); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); }

16 COMP 110: Spring 200916 Opening a Text File outputStream = new PrintWriter(fileName); Calls the constructor of the PrintWriter class Opens the text file with the name fileName ("out.txt") If the file already exists, its contents are overwritten If the file doesn’t exist, an empty file with that name is created Since the constructor might throw a FileNotFoundException, we must enclose it in a try block Also need a corresponding catch block to catch the exception

17 COMP 110: Spring 200917 Writing to a Text File Once the file is open, we can write to it The PrintWriter class has methods print & println that work just like methods in System.out Data is written to the file instead of to screen Calls to these methods do not have to be within a try block outputStream.println("I’m writing to a file!"); outputStream.print("Another message!");

18 COMP 110: Spring 200918 Buffering When you write to a file, the data may not immediately reach its destination This is because of buffering The output stream will wait until it has collected a large amount of data to write before it writes anything to the file itself This is done for efficiency

19 COMP 110: Spring 200919 Closing a Text File Once you’re finished writing to the file you should disconnect the stream from the file itself This is done using the close method outputStream.close(); //close the file Calling the close() method ensures that any remaining data is written out to the file

20 COMP 110: Spring 200920 Example: Writing to a File import java.io.*; public class TextFileOutput { public static void main(String[] args) { String fileName = "out.txt"; PrintWriter outputStream = null; try { outputStream = new PrintWriter(fileName); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); } //print the numbers 0-9 to the file one on each line for(int i = 0; i < 10; i++) { outputStream.println(i); } outputStream.close(); //close the file }

21 COMP 110: Spring 200921 Summary: Writing to a File Open the file Create a PrintWriter object Pass the name of the file you want to write to the constructor Use try/catch blocks to catch a possible FileNotFoundException Write to the file Use the print/println methods of the PrintWriter object you created Close the file

22 COMP 110: Spring 200922 Reading from a Text File We can read from a text file using an object of the Scanner class Recall, we have used the scanner class to read input from the keyboard, as in: Scanner keyboard = new Scanner(System.in); We can create a scanner object to read from a file in the following way String fileName = "in.txt"; Scanner inputFile = new Scanner(new File(fileName));

23 COMP 110: Spring 200923 Opening a File for Reading The Scanner class constructor can also throw a FileNotFoundException We must enclose it in a try block String fileName = "in.txt"; Scanner inputFile = null; try { inputFile = new Scanner(new File(fileName)); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); }

24 COMP 110: Spring 200924 Reading from a Text File All methods of the Scanner class we have used previously can also be used to read from a text file nextInt(), nextDouble(), nextLine(), etc The Scanner class also has methods to determine whether more input data remains in the file hasNext(), hasNextDouble(), hasNextInt(), hasNextLine() etc.

25 COMP 110: Spring 200925 Read a File & Print to Screen import java.util.Scanner; import java.io.*; public class TextFileInput { public static void main(String[] args) { String fileName = "in.txt"; //the name of the file we want to open Scanner inputFile = null; try { inputFile = new Scanner(new File(fileName)); //open the file } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); } while(inputStream.hasNextLine()) { String line = inputStream.nextLine(); //read a line of text from the file System.out.println(line); //print the line of text to screen } inputFile.close(); //close the file }

26 COMP 110: Spring 200926 Closing an Input File One you’re finished reading from a text file, you should close the stream Allowing you to write to it later etc This is done using the close method inputFile.close();

27 COMP 110: Spring 200927 Summary: Reading from a File Open the file Create a Scanner object Use try/catch blocks to catch a possible FileNotFoundException Read from the file Use the methods of the Scanner object you created Close the file

28 COMP 110: Spring 200928 The Class File Java provides the class File as a way of representing file names A string such as "out.txt" may be a file name, but Java treats it as any other String object Passing "out.txt" to the constructor of the class file allows us to treat this as a file name in Java

29 COMP 110: Spring 200929 Using the Class File The class File has a constructor that takes in the name of the file Example File outFile = new File("out.txt"); File inFile = new File("in.txt");

30 COMP 110: Spring 200930 Using the Class File The class File also defines several useful methods for working w/ files public boolean canRead() Tests whether the program can read from the file public boolean canWrite() Tests whether the program can write to the file public boolean delete() Attempts to delete the file. Returns true on success public boolean exists() Tests whether the file currently exists public String getName() Returns the name of the file public String getPath() Returns the path name of the file public long length() Returns the length of the file in bytes

31 COMP 110: Spring 200931 Using Path Names When specifying a file name such as "out.txt", the file is assumed to be in the same directory as your program We can refer to a file in a different directory using a path name instead of just the file name Example "C:\\COMP110\\out.txt"

32 COMP 110: Spring 200932 Using Path Names A full path name is a complete path name starting at the root directory e.g. "C:\\COMP110\\out.txt" A relative path name is a path to the file starting at the directory containing your program e.g. "files\\out.txt"

33 COMP 110: Spring 200933 Using Path Names Why use two backslashes (\\) when specifying file paths in Java? e.g. "C:\\COMP110\\out.txt" Recall that backslash is the escape character in Java '\n' – newline, '\t' – tab, etc "\\" in a string means a single backslash

34 COMP 110: Spring 200934 Using File Paths To get around having to use two backslashes, we can use UNIX-style file paths e.g. "C:/COMP110/out.txt" This works on both Windows and UNIX!

35 COMP 110: Spring 200935 File Names What if we don’t know the name of the file when writing the program? Ask the user for the name of the file!

36 COMP 110: Spring 200936 Programming Demo Write a program that searches a file of numbers and displays the largest number, smallest number and average of all numbers in the file Write the statistics out to a separate file Ask the user for the names of the input/output files

37 COMP 110: Spring 200937 Programming Demo Programming

38 COMP 110: Spring 200938 Friday Recitation Short lab Work on Program 5


Download ppt "COMP 110: Spring 20091 Announcements Program 5 Milestone 1 was due today Program 4 has been graded."

Similar presentations


Ads by Google