COMP 110 Introduction to Programming Tyler Johnson Apr

  • Slides: 42
Download presentation
COMP 110: Introduction to Programming Tyler Johnson Apr 15, 2009 MWF 11: 00 AM-12:

COMP 110: Introduction to Programming Tyler Johnson Apr 15, 2009 MWF 11: 00 AM-12: 15 PM Sitterson 014

Announcements Program 5 Milestone 1 due tonight by 5 pm Program 4 has been

Announcements Program 5 Milestone 1 due tonight by 5 pm Program 4 has been graded 2 COMP 110: Spring 2009

Milestone 1 comprises tasks that make up 50% of the credit on Program 5

Milestone 1 comprises tasks that make up 50% of the credit on Program 5 I will be averaging your grades for Milestone 1 and the final Submission when calculating your grade for that 50% of credit i. e. no Milestone 1 submission = 75% max grade 3 COMP 110: Spring 2009

Questions? 4 COMP 110: Spring 2009

Questions? 4 COMP 110: Spring 2009

Today in COMP 110 Review Exceptions Basic File I/O Programming Demo 5 COMP 110:

Today in COMP 110 Review Exceptions Basic File I/O Programming Demo 5 COMP 110: Spring 2009

Review Exceptions 6 COMP 110: Spring 2009

Review Exceptions 6 COMP 110: Spring 2009

Exceptions An exception is an object that signals the occurrence of an unusual (exceptional)

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 7 COMP 110: Spring 2009

The try Block A try block contains the basic algorithm for when everything goes

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 = score. Sum/num. Games; } 8 COMP 110: Spring 2009

The catch Block The catch block is used to deal with any exceptions that

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(Arithmetic. Exception e) { System. out. println(e. get. Message()); System. out. println("Cannot compute average for 0 games"); } 9 COMP 110: Spring 2009

Example Using Exception Handling (try/catch blocks) int score = keyboard. next. Int(); int score.

Example Using Exception Handling (try/catch blocks) int score = keyboard. next. Int(); int score. Sum = 0; int num. Games = 0; while(score >= 0) { score. Sum += score; num. Games++; score = keyboard. next. Int(); } double average = 0; try { average = score. Sum/num. Games; } catch(Arithmetic. Exception e) { System. out. println(e. get. Message()); System. out. println("Cannot compute average for 0 games"); } 10 COMP 110: Spring 2009

Basic File I/O Sections 10. 1 -10. 3 in text 11 COMP 110: Spring

Basic File I/O Sections 10. 1 -10. 3 in text 11 COMP 110: Spring 2009

Files Your music, pictures, videos, even your Java programs are stored on your computer

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 12 COMP 110: Spring 2009

Streams Writing to & reading from files is done using a stream A stream

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 13 COMP 110: Spring 2009

Streams Input Stream Output Stream Keyboard Input Stream CD 14 Monitor Output Stream Program

Streams Input Stream Output Stream Keyboard Input Stream CD 14 Monitor Output Stream Program Hard drive COMP 110: Spring 2009

Stream Class In Java, streams are objects of special stream class Scanner objects are

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 15 COMP 110: Spring 2009

File I/O stands for File Input/Output Why use files for input/output? Permanent data storage

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 16 COMP 110: Spring 2009

Text Files vs Binary Files All files are stored as binary digits (bits) In

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 read/edited by humans All other files are binary files Your music & picture files Binary files cannot be read/edited by humans 17 COMP 110: Spring 2009

Creating a Text File The Print. Writer class is provided by Java to aid

Creating a Text File The Print. Writer 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 18 COMP 110: Spring 2009

Opening a Text File //need to import java. io. Print. Writer //& java. io.

Opening a Text File //need to import java. io. Print. Writer //& java. io. File. Not. Found. Exception String file. Name = "out. txt"; Print. Writer output. Stream = null; try { output. Stream = new Print. Writer(file. Name); } catch(File. Not. Found. Exception e) { System. out. println("Error opening file " + file. Name); System. exit(0); } 19 COMP 110: Spring 2009

Opening a Text File output. Stream = new Print. Writer(file. Name); Calls the constructor

Opening a Text File output. Stream = new Print. Writer(file. Name); Calls the constructor of the Print. Writer class Opens the text file with the name file. Name ("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 File. Not. Found. Exception, we must enclose it in a try block Also need a corresponding catch block to catch the exception 20 COMP 110: Spring 2009

Writing to a Text File Once the file is open, we can write to

Writing to a Text File Once the file is open, we can write to it The Print. Writer 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 output. Stream. println("I’m writing to a file!"); output. Stream. print("Another message!"); 21 COMP 110: Spring 2009

Buffering When you write to a file, the data may not immediately reach its

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 22 COMP 110: Spring 2009

Closing a Text File Once you’re finished writing to the file you should disconnect

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 output. Stream. close(); //close the file Calling the close() method ensures that any remaining data is written out to the file 23 COMP 110: Spring 2009

Example: Writing to a File import java. io. *; public class Text. File. Output

Example: Writing to a File import java. io. *; public class Text. File. Output { public static void main(String[] args) { String file. Name = "out. txt"; Print. Writer output. Stream = null; try { output. Stream = new Print. Writer(file. Name); } catch(File. Not. Found. Exception e) { System. out. println("Error opening file " + file. Name); System. exit(0); } //print the numbers 0 -9 to the file on each line for(int i = 0; i < 10; i++) { output. Stream. println(i); } 24 } } output. Stream. close(); //close the file COMP 110: Spring 2009

Summary: Writing to a File Open the file Create a Print. Writer object •

Summary: Writing to a File Open the file Create a Print. Writer object • Pass the name of the file you want to write to the constructor Use try/catch blocks to catch a possible File. Not. Found. Exception Write to the file Use the print/println methods of the Print. Writer object you created Close the file 25 COMP 110: Spring 2009

Reading from a Text File We can read from a text file using an

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 file. Name = "in. txt"; Scanner input. File = new Scanner(new File(file. Name)); 26 COMP 110: Spring 2009

Opening a File for Reading The Scanner class constructor can also throw a File.

Opening a File for Reading The Scanner class constructor can also throw a File. Not. Found. Exception We must enclose it in a try block String file. Name = "in. txt"; Scanner input. File = null; try { input. File = new Scanner(new File(file. Name)); } catch(File. Not. Found. Exception e) { System. out. println("Error opening file " + file. Name); System. exit(0); } 27 COMP 110: Spring 2009

Reading from a Text File All methods of the Scanner class we have used

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 next. Int(), next. Double(), next. Line(), etc The Scanner class also has methods to determine whether more input data remains in the file has. Next(), has. Next. Double(), has. Next. Int(), has. Next. Line() etc. 28 COMP 110: Spring 2009

Read a File & Print to Screen import java. util. Scanner; import java. io.

Read a File & Print to Screen import java. util. Scanner; import java. io. *; public class Text. File. Input { public static void main(String[] args) { String file. Name = "in. txt"; //the name of the file we want to open Scanner input. File = null; try { input. File = new Scanner(new File(file. Name)); //open the file } catch(File. Not. Found. Exception e) { System. out. println("Error opening file " + file. Name); System. exit(0); } while(input. Stream. has. Next. Line()) { String line = input. Stream. next. Line(); //read a line of text from the file System. out. println(line); //print the line of text to screen } input. File. close(); //close the file } } 29 COMP 110: Spring 2009

Closing an Input File One you’re finished reading from a text file, you should

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 input. File. close(); 30 COMP 110: Spring 2009

Summary: Reading from a File Open the file Create a Scanner object Use try/catch

Summary: Reading from a File Open the file Create a Scanner object Use try/catch blocks to catch a possible File. Not. Found. Exception Read from the file Use the methods of the Scanner object you created Close the file 31 COMP 110: Spring 2009

The Class File Java provides the class File as a way of representing file

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 32 COMP 110: Spring 2009

Using the Class File The class File has a constructor that takes in the

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

Using the Class File The class File also defines several useful methods for working

Using the Class File The class File also defines several useful methods for working w/ files public boolean can. Read() • Tests whether the program can read from the file public boolean can. Write() • 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 get. Name() • Returns the name of the file public String get. Path() • Returns the path name of the file public long length() • Returns the length of the file in bytes 34 COMP 110: Spring 2009

Using Path Names When specifying a file name such as "out. txt", the file

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: \COMP 110\out. txt" 35 COMP 110: Spring 2009

Using Path Names A full path name is a complete path name starting at

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

Using Path Names Why use two backslashes (\) when specifying file paths in Java?

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

Using File Paths To get around having to use two backslashes, we can use

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

File Names What if we don’t know the name of the file when writing

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! 39 COMP 110: Spring 2009

Programming Demo Write a program that searches a file of numbers and displays the

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 40 COMP 110: Spring 2009

Programming Demo Programming 41 COMP 110: Spring 2009

Programming Demo Programming 41 COMP 110: Spring 2009

Friday Recitation Help with Program 5 42 COMP 110: Spring 2009

Friday Recitation Help with Program 5 42 COMP 110: Spring 2009