Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Lecture 15: I/O and Parsing
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
ELC 310 Day 21. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Agenda Questions? Capstone Proposals Overdue  4 Submitted  3 Accepted, 1 in negotiations.
“OUT,OUT” ROBERT FROST.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
Introduction to Objects and Input/Output
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
CS 206 Introduction to Computer Science II 09 / 04 / 2008 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
String Tokenization What is String Tokenization?
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
10-1 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Lab 2 Primer Assignment 3 Structure File I/O More parsing and HTTP Formatting.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Chapter 10 Exceptions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Reading from a file and Writing to a file
10 Exceptions Software Solutions Lewis & Loftus java 5TH EDITION
Strings and File I/O.
Chapter 10 Exceptions.
Streams and File I/O Chapter 14.
Reading and Writing Text Files
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Chapter 10 Exceptions.
File Input and Output.
Presentation transcript:

Chapter 10 Exceptions and File I/O

© 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on:  the purpose of exceptions  exception messages  the try-catch statement  propagating exceptions  the exception class hierarchy  GUI mnemonics and tool tips  more GUI components and containers

© 2004 Pearson Addison-Wesley. All rights reserved10-3 Outline Exception Handling The try-catch Statement Exception Propagation Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes

© 2004 Pearson Addison-Wesley. All rights reserved10-4 File I/O Reading in from a file Java has several classes that handle input from a file. One of these is FileReader. Declaring an object of type FileReader will allow a program to read in one character at a time with the read method But generally, one wants to read in more than one character at a time, say a line at a time. For this we use the BufferedReader class together with the FileReader class. It has the method readLine(), which will read in a line of a file.

© 2004 Pearson Addison-Wesley. All rights reserved10-5 File I/O -Reading in from a file Declaring an object of type BufferedReader:  BufferedReader filein=new BufferedReader(new FileReader( “data.dat”));  You can now use the filein object to readin a line of a file with a statement String input = filein.readLine(); Read in an entire file as follows:  BufferedReader filein = new BufferedReader(new FileReader(“data.dat”)); //declaring object to read in  while((str =filein.readLine()) != null) //reading in a line and //checking whether at the end of file  System.out.println(str); //printing out the line Remember the method with these statements will need a throws IOException in the header or you will have to have a try…catch block around them

© 2004 Pearson Addison-Wesley. All rights reserved10-6 File I/O Writing out to a file Java has a number of classes that can be used to write data out to a file. We will use two of them together, PrintWriter and FileWriter FileWriter allows writing to a file one character at a time and PrintWriter allows writing a line at a time, if used with FileWriter. The methods that PrintWriter has to write with are print(), and println() Because print() and println(), as we have seen already are overloaded, you can write out ints, doubles, Strings or concatenated combinations.

© 2004 Pearson Addison-Wesley. All rights reserved10-7 File I/O Writing out to a file To declare an object of PrintWriter Class : PrintWriter fileout = new PrintWriter(new FileWriter(“dataout.dat”)); To to write a line to your file with this object:  fileout.println(“My name is “+name); To read write out an array of ints, one number per line, after declaring fileout as above:  int arr [] = { 1,2,3,4,5,6,7,8,9,10,11,13,15,17,20,30,23};  for(int index=0;index<arr.length;index++) fileout.println( “arr[index] + “ is on the “ +index + “ line”); Remember, again you would need a throws IOException in the header of the method with these statements or have to surround the statements with a try..catch block.

© 2004 Pearson Addison-Wesley. All rights reserved10-8 File I\O -Reading in and Writing out To read in from a file data.dat and write out what you have read in to a file dataout.dat:  BufferedReader input = new BufferedReader(new FileReader(“data.dat”));  PrintWriter output = new PrintWriter(new FileWriter(“dataout.dat”));  String str;  try {  while((str = input.readLine()) != null) output.println(str);  }catch(FileNotFoundException fnfe) { System.out.println(fnfe);  }catch(IOException oe) { System.out.println(oe); }}

© 2004 Pearson Addison-Wesley. All rights reserved10-9 File I/O - parsing the line of input Once you have read in a line from a data file, say with the statement  BufferedReader input = new BufferedReader(new FileReader(“data.dat”));  String str = input.readLine(); You have a String variable, str, with a line from data.dat. If the line just contains a statement that you want to print out you can just say System.out.println(str); and be finished But suppose instead the line contains a set of numbers That you want to add up and take an average of. In this case you need some way of separating the numbers. In Java, there is a class that allows you to do that, the String Tokenizer class.

© 2004 Pearson Addison-Wesley. All rights reserved10-10 Separating the data in a String The String Tokenizer class allows you to parse a String (line) of data and extract each data item in the String. To declare a String Tokenizer object:  StringTokenizer tokenizer = new StringTokenizer(str);  //where str is a line of data read in. So you declare and instantiate a new tokenizer object for each line (String) of data read in from a file. Then you use a loop to search the String str to extract each data item.  while(tokenizer.hasMoreTokens()) { //checking if at end String word = tokenizer.nextToken(); //getting next word numwords++; //counting the words }

© 2004 Pearson Addison-Wesley. All rights reserved10-11 Separating the data in a String When you declare a String Tokenizer object like this:  StringTokenizer tokenizer = new StringTokenizer(str); The separator for the data will automatically be a blank, so words or numbers separated by blanks can be extracted You can specify what the separator will be:  StringTokenizer=new StringTokenizer(str, “,”); Now the separator will be a comma.

© 2004 Pearson Addison-Wesley. All rights reserved10-12 Reading in an array of data in a file with 10 numbers per line Public static void main(String args[]) throws IOException { BufferedReader input = new BufferedReader(new FileReader(“data.dat”)); //declaring input object int arr [] = new int[10][30]; //declaring array to hold input int I = 0; String str; while((str =input.readLine()) != null) //reading until eof { StringTokenizer tok=new StringTokenizer(str); //data //separated by blanks for(int j = 0; j<arr[I]length;j++) while(tok.hasMoreTokens()) //at end of line arr[ I][j]=Integer.parseInt(tok.nextToken()); I++; } }

© 2004 Pearson Addison-Wesley. All rights reserved10-13 File I/O- Reading in text file and counting the words Suppose we have a file with the following words in it: “Out, out, brief candle, life’s but a walking shadow, a poor player who struts and frets his hour upon the stage and then is heard no more; it is a tale told by an idiot, full of sound and fury signifying nothing”

© 2004 Pearson Addison-Wesley. All rights reserved10-14 File I/O -reading in text file and counting words cont. Then to read in that file and count the number of words in it: BufferedReader input=new BufferedReader(new FileReader(“data.dat”)); //get an object to use for reading String str; //String variable to hold input int numwords=0; //int to hold word count while((str=input.readLine()) != null) //loop reading in lines { StringTokenizer tok = new StringTokenizer(str); //Tokenizer for //each line while(tok.hasMoreTokens()) //loop for getting each word on //line { tok.nextToken(); //getting next word numwords++; //adding another word to count } }

© 2004 Pearson Addison-Wesley. All rights reserved10-15 Summary Chapter 10 has focused on: the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hierarchy GUI mnemonics and tool tips more GUI components and containers