OOP
File Handling
Course: Object Oriented Programming (CS2005)
Instructor: Dr. Benish Fida
Outline
• Concept of an I/O stream
• Binary files and text files
• Save data in a file
• Read data from a file
I/O Overview
• I/O = Input/Output
• Input can be from keyboard or a file
• Output can be to display (screen) or a file
• Advantages of file I/O
• permanent copy
• output from one program can be input to another
• input can be automated (rather than entered manually)
Streams
• Stream: an object that either delivers data to its destination (screen,
file, etc.) or that takes data from a source (keyboard, file, etc.)
• It acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
• [Link] is an input stream
• Output stream: a stream that accepts output from a program
• [Link] is an output stream
• A stream connects a program to an I/O object
• [Link] connects a program to the screen
• [Link] connects a program to the keyboard
Text vs Binary Files
• Text files are more readable by humans
• Binary files are more efficient
• Computers read and write binary files more easily than text
• Java binary files are portable
• They can be used by Java on different machines
• Reading and writing binary files is normally done by a program
• Text files are used only to communicate with humans
Java Text Files Java Binary Files
Source files Executable files (created by compiling source
files)
Text File I/O
• Important classes for text file output (to the file)
• PrintWriter
• FileOutputStream [or FileWriter]
• Important classes for text file input (from the file):
• BufferedReader
• FileReader
• FileOutputStream and FileReader take file names as arguments.
• PrintWriter and BufferedReader provide useful methods for easier
writing and reading.
• Usually need a combination of two classes
• To use these classes your program needs a line like the following:
import [Link].*;
Text File Output
• To open a text file for output: connect a text file to a stream for
writing
PrintWriter outputStream =
new PrintWriter(new FileOutputStream("[Link]"));
• Similar to the long way:
FileOutputStream s = new FileOutputStream("[Link]");
PrintWriter outputStream = new PrintWriter(s);
• Create a PrintWriter object
- which uses FileOutputStream to open a text file
• FileOutputStream “connects” PrintWriter to a text file.
Methods for PrintWriter
• Similar to methods for [Link]
• println
[Link](count + " " + line);
• print
• format
• flush: write buffered output to disk
• close: close the PrintWriter stream (and file)
Text File Output
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream("[Link]"));
}
catch(FileNotFoundException e)
{
[Link]("Error opening the file [Link]. “
+ [Link]());
[Link](0);
}
Text File Output
[Link]("Enter three lines of text:");
String line = null;
int count;
for (count = 1; count <= 3; count++)
{
line = [Link]();
[Link](count + " " + line);
}
[Link]();
[Link]("... written to [Link].");
}
Overwriting a File
• Opening an output file creates an empty file
• Opening an output file creates a new file if it does not already exist
• Opening an output file that already exists eliminates the old file and
creates a new, empty one
– data in the original file is lost
• To see how to check for existence of a file, see the section of the text
that discusses the File class (later slides).
Overwriting a File
• To add/append to a file instead of replacing it, use a different
constructor for FileOutputStream:
outputStream = new PrintWriter(new FileOutputStream("[Link]",
true));
• Second parameter: append to the end of the file if it exists?
• Sample code for letting user tell whether to replace or append:
Closing a File
• An output file should be closed when you are done writing to it (and
an input file should be closed when you are done reading from it).
• Use the close method of the class PrintWriter (BufferedReader also
has a close method).
• For example, to close the file opened in the previous example:
[Link]();
• If a program ends normally it will close any files that are open.
Text File Input
• To open a text file for input: connect a text file to a stream for reading
• Goal: a BufferedReader object,
– which uses FileReader to open a text file
• FileReader “connects” BufferedReader to the text file
• For example:
BufferedReader inStream =
new BufferedReader(new FileReader(“[Link]"));
• Similarly, the long way:
FileReader s = new FileReader(“[Link]");
BufferedReader inStream = new BufferedReader(s);
BufferedReader Methods
• readLine: read a line into a String
• No methods to read numbers directly, so read numbers as Strings and
then convert them (StringTokenizer later)
• read: read a char at a time
• close: close BufferedReader stream
Exception Handling with File I/O
Catching IOExceptions
• IOException is a predefined class
• File I/O might throw an IOException
• catch the exception in a catch block that at least prints an error
message and ends the program
• FileNotFoundException is derived from IOException
• Therefor any catch block that catches IOExceptions also catches
FileNotFoundExceptions
• Put the more specific one first (the derived one) so it catches specifically file-
not-found exceptions
• Then you will know that an I/O error is something other than file-not-found
public static void main(String[] args)
{
String fileName = null; // outside try block, can be used in catch
try
{ Scanner keyboard = new Scanner([Link]);
[Link]("Enter file name:");
Reading a File fileName = [Link]();
BufferedReader inputStream =
new BufferedReader(new FileReader(fileName));
String line = null;
line = [Link]();
[Link]("The first line in " + filename + " is:");
[Link](line);
// . . . code for reading second line not shown here . . .
[Link]();
}
catch(FileNotFoundException e)
{
[Link]("File " + filename + " not found.");
}
catch(IOException e)
{
[Link]("Error reading from file " + fileName);
}
}
[Link]()
try
{
…
}
catch (FileNotFoundException e)
{
[Link](filename + “ not found”);
[Link](“Exception: “ +
[Link]());
[Link](-1);
}
End of File Testing
• When readLine tries to read beyond the end of a text file it returns
the special value null
• so you can test for null to stop processing a text file
• read returns -1 when it tries to read beyond the end of a text file
• the int value of all ordinary characters is nonnegative
• Neither of these two methods (read and readLine) will throw an
EOFException.
End of File Testing
int count = 0;
String line = [Link]();
while (line != null)
{
count++;
[Link](count + " " + line);
line = [Link]();
}
File Class
• A file name like "[Link]" has only String properties
• File has some very useful methods
• exists: tests if a file already exists
• canRead: tests if the OS will let you read a file
• canWrite: tests if the OS will let you write to a file
• delete: deletes the file, returns true if successful
• length: returns the number of bytes in the file
• getName: returns file name, excluding the preceding path
• getPath: returns the path name—the full name
File numFile = new File(“[Link]”);
if ([Link]())
[Link]([Link]());
File Objects and Filename
• FileInputStream and FileOutputStream have constructors that take a
File argument as well as constructors that take a String argument
PrintWriter fileOutStream = new PrintWriter(new
FileOutputStream(“[Link]”));
File fileOut = new File(“[Link]”);
if ([Link]())
PrintWriter fileOutStream = new PrintWriter(new
FileOutputStream(fileOut));
Use of Scanner
• Instead of BufferedReader with FileReader, then
StringTokenizer
• Use Scanner with File:
Scanner inFile =
new Scanner(new File(“[Link]”));
• Similar to Scanner with [Link]:
Scanner keyboard =
new Scanner([Link]);
Reading Line of Characters
Scanner inFile = new Scanner(new
File(“[Link]"));
String line;
while ([Link]())
{
line = [Link]();
// …
}
String line;
while ([Link]())
{
line = [Link]();
Scanner parseLine = new Scanner(line) //
Scanner again!
name = [Link]();
id = [Link]();
balance = [Link]();
// … new Account(name, id, balance);
}
// Name, id, balance
Scanner inFile = new Scanner(new File(“[Link]"));
String line;
while ([Link]())
{
line = [Link]();
Account account = new Account(line);
}
--------------------
public Account(String line) // constructor
{
Scanner accountLine = new Scanner(line);
_name = [Link]();
_id = [Link]();
_balance = [Link]();
}
BufferedReader vs Scanner
• BufferedReader
• readLine() returns null
• read() returns -1
• Scanner
• nextLine() throws exception
• needs hasNextLine() to check first
• nextInt(), hasNextInt(), …
BufferedReader vs Scanner
BufferedReader inFile = …
line = [Link]();
while (line != null)
{
// …
line = [Link]();
}
-------------------
Scanner inFile = …
while ([Link]())
{
line = [Link]();
// …
}
Summary
• Text files contain strings of printable characters; they look intelligible
to humans when opened in a text editor.
• Binary files contain numbers or data in non-printable codes; they look
unintelligible to humans when opened in a text editor.
• Always check for the end of the file when reading from a file. The way
you check for end-of-file depends on the method you use to read
from the file.
• A file name can be read from the keyboard into a String variable and
the variable used in place of a file name.
• The class File has methods to test if a file exists and if it is read-
and/or write-enabled.