File Operations
File Operations
Classes
• PhoneBookEntry: // COMPLETED LAST WEEK
• PhoneBook: // TO DO
Finished PhoneBookEntry application
Worked example class PhoneBookEntry {
public PhoneBook( ) {
entries = new PhoneBookEntry[MAX_ENTRIES];
}
PhoneBookTest application
Worked example Lets now write an application to use our new
PhoneBook class and test our code:
}
• However, this is far from ideal!!
Worked example • We don’t want to have to set a fixed size for
our phone book in advance.
• With a little more work we can make our
storage more intelligent, by following the
psuedocode below when we add an entry:
public PhoneBook( ) {
entries = new PhoneBookEntry[maxEntriesLength];
}
}
EXAMPLE: LinearSearch Folder
Finding Numbers
Worked example Lets implement a numberFor method, so we can search the
number for a given name. We could use a linear search algorithm:
Linear search
Linear search is a simple search algorithm that can find the position
of a specified value (called the key) within an array. The key is simply
compared to each element in turn and its position is returned if it is
found. If it is not found then -1 is returned.
import java.util.Vector;
public PhoneBook( ) {
entries = new Vector<PhoneBookEntry>();
}
........
}
The usual question at this stage is:
Worked example
Why Vector?
public PhoneBook( ) {
entries = new ArrayList<PhoneBookEntry>();
}
........
}
Reading text files
Reading Text Files Using the Scanner class
try {
System.out.println(
"Trying Integer.parseInt( \"NOT AN INT\" )" );
int i = Integer.parseInt( "Not an int" );
}
catch ( Exception e ) {
System.out.println("Some error" + e);
Example
e.printStackTrace();
}
finally {
System.out.println( "Finally always reached" );
}
}
}
General form
try {
// Code that may throw exception
}
General Form
catch (ExceptionType e) {
// Handle exception
}
finally { // Optional
// Tidy up
}
Definition
The Java virtual machine uses a call stack to track
the currently executing method and the method that
called the current method. In any Java application
Stack Traces
the main method is always the first method on the
stack and the last method to leave the stack.
try {
while ( in.hasNextLine() ) {
System.out.println( new StringBuffer(
in.nextLine()).reverse() );
}
in.close();
}
catch ( Exception e ) {
System.out.println( e );
}
}
}
EXAMPLE: SumDoubles Folder
try {
Scanner in = new Scanner( new File(args[0]) );
double total = 0;
while (in.hasNextDouble()) {
total += in.nextDouble();
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Reading a phone book from text file
Worked example
• We can represent a phone
book in a text file by having a
particular entry on each line
• Each line would contain a
name and a number
separated by a space
EXAMPLE: PhoneBookLoader Folder
import java.util.Scanner;
import java.io.File;
Worked example public static PhoneBook loadPhoneBook( String filename ) throws Exception {
File fileIn = new File( filename );
try {
Scanner in = new Scanner( fileIn );
PhoneBook book = new PhoneBook();
while( in.hasNextLine() ) {
// Get a line of the text file
String line = in.nextLine();
return book;
}
catch( Exception e ) {
System.out.println( "Problem reading file: " + filename );
throw e; // re-raise exception
}
}
files.
• The Reader and Writer classes and their
subclasses are used to handle text files.
• The Reader and Writer classes are abstract.
• To perform text input/output we use one the
subclasses of Reader or Writer
• FileReader: constructs a
Reader that can read from a
file. Only provides low-level
Writing files
read methods.
• BufferedReader: wraps
around a FileReader and
provides a high-level
readLine method.
EXAMPLE: Text Folder
ReaderTest.java
+
Text Files
WriterTest.java
Use subclasses of InputStream
and OutputStream classes:
Date d = new Date();
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( "test.dat" ) );
out.writeObject( d );
out.close();
ObjectInputStream in = new ObjectInputStream( new FileInputStream( "test.dat" ) );
Date sc = (Date)in.readObject();
in.close();
• After a serialized object has been written into a file, it can be read
from the file and deserialized. That is, the type information and
bytes that represent the object and its data can be used to
recreate the object in memory.
ReadTest.java
+
Binary Files
WriteTest.java
Binary Text
Compact files Easy for user to
Binary vs Text
read
Easier to code More portable
Includes some More complex to
error checking code
Awkward if classes Error checking
change needs to be coded
Questions