Lecture 7 File I/O (and a little bit about exceptions)‏

Slides:



Advertisements
Similar presentations
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
Advertisements

Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
CIS 1068 Program Design and Abstraction
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
Files and Streams CS 21a Chapter 11 of Horstmann.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 16 – Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Chapter 16 – Files and Streams. Announcements Only responsible for 16.1,16.3 Only responsible for 16.1,16.3 Other sections “encouraged” Other sections.
A Few Exceptions, A Little IO, and Persistent Objects Rick Mercer.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Handling errors Exception handling and throwing Simple file processing.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Two Ways to Store Data in a File Text format Binary format.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Chapter 16 Streams. Chapter Goals To be able to read and write text files To become familiar with the concepts of text and binary formats To learn about.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Working with files. RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program.
Fall 2006Adapted from Java Concepts Companion Slides1 Files and Streams Advanced Programming ICOM 4015 Lecture 16 Reading: Java Concepts Chapter 16.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Two Ways to Store Data in a File  Text format  Binary format.
CHAPTER 15 STREAMS. CHAPTER GOALS To be able to read and write files To become familiar with the concepts of text and binary files To be able to read.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
CSE 501N Fall ‘09 18: Files and Streams 06 November 2009 Nick Leidenfrost.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Chapter 10 – Input/Output and Exception Handling Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Chapter 11 Exceptions and Input/Output Operations.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Files and Serialization. Files Used to transfer data to and from secondary storage.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Exception Handling.
File - CIS 1068 Program Design and Abstraction
Streams & File Input/Output (I/O)
Introduction Exception handling Exception Handles errors
I/O Basics.
CSE 501N Fall ’09 17: Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
Chapter 15 – Exception Handling
Working with files.
Working with files.
CSS 161: Fundamentals of Computing
Exception Handling.
Chapter 16 Streams.
Chapter 11 Input/Output Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

Lecture 7 File I/O (and a little bit about exceptions)‏

Chapter Goals To be able to read and write text files To become familiar with the concepts of text and binary formats To understand when to use sequential and random file access To understand the difference between checked and unchecked exceptions To learn how to catch exceptions

Reading Text Files Simplest way to read text: use Scanner class To read from a disk file, construct a FileReader Then, use the FileReader to construct a Scanner object Use the Scanner methods to read data from file  next, nextLine, nextInt, and nextDouble FileReader reader = new FileReader("input.txt"); Scanner in = new Scanner(reader);

Writing Text Files To write to a file, construct a PrintWriter object If file already exists, it is emptied before the new data are written into it If file doesn't exist, an empty file is created PrintWriter out = new PrintWriter("output.txt"); Continued…

Writing Text Files Use print and println to write into a PrintWriter : You must close a file when you are done processing it: Otherwise, not all of the output may be written to the disk file out.println(29.95); out.println(new Rectangle(5, 10, 15, 25)); out.println("Hello, World!"); out.close();

A Sample Program Reads all lines of a file and sends them to the output file, preceded by line numbers Sample input file: Continued… Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go!

A Sample Program Program produces the output file: Program can be used for numbering Java source files /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go!

File LineNumberer.java 01: import java.io.FileReader; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args)‏ 09: { 10: Scanner console = new Scanner(System.in); 11: System.out.print("Input file: "); 12: String inputFileName = console.next(); 13: System.out.print("Output file: "); 14: String outputFileName = console.next(); 15: 16: try 17: { Continued…

File LineNumberer.java 18: FileReader reader = new FileReader(inputFileName); 19: Scanner in = new Scanner(reader); 20: PrintWriter out = new PrintWriter(outputFileName); 21: int lineNumber = 1; 22: 23: while (in.hasNextLine())‏ 24: { 25: String line = in.nextLine(); 26: out.println("/* " + lineNumber + " */ " + line); 27: lineNumber++; 28: } 29: 30: out.close(); 31: } 32: catch (IOException exception)‏ 33: { Continued…

File LineNumberer.java 34: System.out.println("Error processing file:" + exception); 35: } 36: } 37: }

Demo A slightly more advanced program with a graphical user interface It asks the user to choose a file containing a music database It reads the file, stores the database in memory and displays (some) of the information in a window

Text and Binary Formats Two ways to store data:  Text format  Binary format

Text Format Human-readable form Sequence of characters  Integer 12,345 stored as characters ' 1 ' ' 2 ' ' 3 ' ' 4 ' ' 5 ' Use Reader and Writer and their subclasses to process input and output To read: To write FileReader reader = new FileReader("input.txt"); FileWriter writer = new FileWriter("output.txt");

Binary Format Data items are represented in bytes Integer 12,345 stored as a sequence of four bytes Use InputStream and OutputStream and their subclasses More compact and more efficient... but stick to text format, please!! Continued…

Binary Format To read: To write FileInputStream inputStream = new FileInputStream("input.bin"); FileOutputStream outputStream = new FileOutputStream("output.bin");

Reading a Single Character from a File in Text Format Use read method of Reader class to read a single character  returns the next character as an int  or the integer -1 at end of file Reader reader =...; int next = reader.read(); char c; if (next != -1) c = (char) next;

Text and Binary Format Use write method to write a single character or byte read and write are the only input and output methods provided by the file input and output classes Java stream package principle: each class should have a very focused responsibility Continued…

Random Access vs. Sequential Access Sequential access  A file is processed a byte at a time  It can be inefficient Random access  Allows access at arbitrary locations in the file  Only disk files support random access System.in and System.out do not !!!  Each disk file has a special file pointer position You can read or write at the position where the pointer is Continued…

Random Access vs. Sequential Access Figure 4: Random and Sequential Access  Each disk file has a special file pointer position You can read or write at the position where the pointer is

RandomAccessFile To get the current position of the file pointer. To find the number of bytes in a file long Usually too much trouble to be worth it. long n = f.getFilePointer(); // of type "long" because files can be very large fileLength = f.length();

Object Streams ObjectOutputStream class can save a entire objects to disk ObjectInputStream class can read objects back in from disk Objects are saved in binary format; hence, you use streams

Writing a BankAccount Object to a File The object output stream saves all instance variables BankAccount b =...; ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("bank.dat")); out.writeObject(b);

Reading a BankAccount Object From a File readObject returns an Object reference Need to remember the types of the objects that you saved and use a cast ObjectInputStream in = new ObjectInputStream( new FileInputStream("bank.dat")); BankAccount b = (BankAccount) in.readObject(); Continued…

Reading a BankAccount Object From a File readObject method can throw a ClassNotFoundException It is a checked exception You must catch or declare it

Serializable Objects that are written to an object stream must belong to a class that implements the Serializable interface. Serializable interface has no methods. class BankAccount implements Serializable {... }

Error Handling Traditional approach: Method returns error code Problem: Forget to check for error code  Failure notification may go undetected Problem: Calling method may not be able to do anything about failure  Program must fail too and let its caller worry about it  Many method calls would need to be checked Continued…

Error Handling Instead of programming for success  you would always be programming for failure: x.doSomething()‏ if (!x.doSomething()) return false;

Throwing Exceptions Exceptions:  Can't be overlooked !!!!!!!!!!!!!!!!!!!!!!!!!!!  Sent directly to an exception handler–not just caller of failed method Throw an exception object to signal an exceptional condition Example: IllegalArgumentException: Continued… illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;

Throwing Exceptions No need to store exception object in a variable: When an exception is thrown, method terminates immediately  Execution continues with an exception handler throw new IllegalArgumentException("Amount exceeds balance");

Example public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... }

Checked and Unchecked Exceptions Two types of exceptions:  Checked The compiler checks that you don't ignore them Due to external circumstances that the programmer cannot prevent Majority occur when dealing with input and output For example, IOException

Checked and Unchecked Exceptions Two types of exceptions:  Unchecked: Extend the class RuntimeException or Error They are the programmer's fault Examples of runtime exceptions: Example of error: OutOfMemoryError NumberFormatException IllegalArgumentException NullPointerException

Checked and Unchecked Exceptions For example, use a Scanner to read a file But, FileReader constructor can throw a FileNotFoundException String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);

Syntax 15.2: Exception Specification accessSpecifier returnType methodName(parameterType parameterName,...) throws ExceptionClass, ExceptionClass,... Example: public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw

Catching Exceptions Example: try { String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

Summary Read and write text files Text and binary formats Sequential and random file access Checked and unchecked exceptions How to catch exceptions