Download presentation
Presentation is loading. Please wait.
1
Lecture 7 File I/O (and a little bit about exceptions)
2
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
3
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);
4
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…
5
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();
6
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!
7
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!
8
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…
9
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…
10
File LineNumberer.java 34: System.out.println("Error processing file:" + exception); 35: } 36: } 37: }
11
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
12
Text and Binary Formats Two ways to store data: Text format Binary format
13
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");
14
Binary Format Data items are represented in bytes Integer 12,345 stored as a sequence of four bytes 0 0 48 57 Use InputStream and OutputStream and their subclasses More compact and more efficient... but stick to text format, please!! Continued…
15
Binary Format To read: To write FileInputStream inputStream = new FileInputStream("input.bin"); FileOutputStream outputStream = new FileOutputStream("output.bin");
16
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;
17
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…
18
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…
19
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
20
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();
21
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
22
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);
23
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…
24
Reading a BankAccount Object From a File readObject method can throw a ClassNotFoundException It is a checked exception You must catch or declare it
25
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 {... }
26
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…
27
Error Handling Instead of programming for success you would always be programming for failure: x.doSomething() if (!x.doSomething()) return false;
28
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;
29
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");
30
Example public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... }
31
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
32
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
33
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);
34
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
35
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"); }
36
Summary Read and write text files Text and binary formats Sequential and random file access Checked and unchecked exceptions How to catch exceptions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.