Streams and File I/O
Anshu Tiwari, CSE, UCER
The Concept of a Stream
• Use of files
• Store Java classes, programs
• Store pictures, music, videos
• Can also use files to store program I/O
• A stream is a flow of input or output data
• Characters
• Numbers
• Bytes
Anshu Tiwari, CSE, UCER
The Concept of a Stream
• Streams are implemented as objects of special stream
classes
Anshu Tiwari, CSE, UCER
Why Use Files for I/O
• Keyboard input, screen output deal with temporary
data
• When program ends, data is gone
• Data in a file remains after program ends
• Can be used next time program runs
• Can be used by another program
Anshu Tiwari, CSE, UCER
Text Files and Binary Files
• All data in files stored as binary digits
• Long series of zeros and ones
• Files treated as sequence of characters called text files
• Java program source code
• Can be viewed, edited with text editor
• All other files are called binary files
• Movie, music files
• Access requires specialized program
Anshu Tiwari, CSE, UCER
Text Files and Binary Files
• A text file and a binary file containing the same
values
Anshu Tiwari, CSE, UCER
Creating a Text File
• Class PrintWriter defines methods needed to
create and write to a text file
• Must import package [Link]
• To open the file
• Declare stream variable for referencing the stream
• Invoke PrintWriter constructor, pass file name as
argument
• Requires try and catch blocks
Anshu Tiwari, CSE, UCER
Creating a Text File
• File is empty initially
• May now be written to with method println
• Data goes initially to memory buffer
• When buffer full, goes to file
• Closing file empties buffer, disconnects from stream
Anshu Tiwari, CSE, UCER
Creating a Text File
import [Link];
import [Link];
import [Link];
public class TextFileOutputDemo
{
public static void main (String [] args)
{
String fileName = "[Link]"; //The name could be read from
//the keyboard.
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter (fileName);
}
Anshu Tiwari, CSE, UCER
Creating a Text File
catch (FileNotFoundException e)
{
[Link] ("Error opening the file " + fileName);
[Link] (0);
}
[Link] ("Enter three lines of text:");
Scanner keyboard = new Scanner ([Link]);
for (int count = 1 ; count <= 3 ; count++)
{
String line = [Link] ();
[Link] (count + " " + line);
}
[Link] ();
[Link] ("Those lines were written to " + fileName);
}
} Anshu Tiwari, CSE, UCER
Creating a Text File
• When creating a file
• Inform the user of ongoing I/O events, program should not
be "silent"
• A file has two names in the program
• File name used by the operating system
• The stream name variable
Anshu Tiwari, CSE, UCER
Appending to a Text File
• Opening a file new begins with an empty file
• If already exists, will be overwritten
• Some situations require appending data to existing file
• Command could be
outputStream =
new PrintWriter(
new FileOutputStream(fileName, true));
• Method println would append data at end
Anshu Tiwari, CSE, UCER
Reading from a Text File
import [Link];
import [Link];
import [Link];
public class TextFileInputDemo
{
public static void main (String [] args)
{
String fileName = "[Link]";
Scanner inputStream = null;
[Link] ("The file “+ fileName +"\ncontains the following lines:\n");
try
{
inputStream = new Scanner (new File (fileName));
}
Anshu Tiwari, CSE, UCER
Reading from a Text File
catch (FileNotFoundException e)
{
[Link] ("Error opening the file " +fileName);
[Link] (0);
}
while ([Link] ())
{
String line = [Link] ();
[Link] (line);
}
[Link] ();
}
}
Anshu Tiwari, CSE, UCER
Reading from a Text File
Additional methods in class Scanner
Anshu Tiwari, CSE, UCER
The Class File
• Class provides a way to represent file names in a
general way
• A File object represents the name of a file
• The object
new File ("[Link]")
is not simply a string
• It is an object that knows it is supposed to name a file
Anshu Tiwari, CSE, UCER
Programming Example
import [Link];
import [Link];
import [Link];
public class TextFileInputDemo2
{
public static void main (String [] args)
{
[Link] ("Enter file name: ");
Scanner keyboard = new Scanner ([Link]);
String fileName = [Link] ();
Scanner inputStream = null;
[Link] ("The file " + fileName + "\n" +"contains the following lines:\n");
try
{
inputStream = new Scanner (new File (fileName));
}
Anshu Tiwari, CSE, UCER
Programming Example
catch (FileNotFoundException e)
{
[Link] ("Error opening the file " +fileName ");
[Link] (0);
}
while ([Link] ())
{
String line = [Link] ();
[Link] (line);
}
[Link] ();
}
}
Anshu Tiwari, CSE, UCER
Using Path Names
• Files opened in our examples assumed to be in same
folder as where program run
• Possible to specify path names
• Full path name
• Relative path name
• Be aware of differences of pathname styles in
different operating systems
Anshu Tiwari, CSE, UCER
Methods of the Class File
• File object is a system-independent abstraction of
file's path name
• Class File has methods to access information about
a path and the files in it
• Whether the file exists
• Whether it is specified as readable or not
• Etc.
Anshu Tiwari, CSE, UCER
Methods of the Class File
Some methods in class File
Anshu Tiwari, CSE, UCER
Defining a Method to Open a Stream
• Method will have a String parameter
• The file name
• Method will return the stream object
• Will throw exceptions
• If file not found
• If some other I/O problem arises
• Should be invoked inside a try block and have
appropriate catch block
Anshu Tiwari, CSE, UCER
Defining a Method to Open a Stream
• Example code
• Example call
Anshu Tiwari, CSE, UCER
Case Study
Processing a Comma-Separated Values File
• A comma-separated values or CSV file is a simple text
format used to store a list of records
• Example from log of a cash register’s transactions for
the day:
Code,Quantity,Price,Description
4039,50,0.99,SODA
9100,5,9.50,T-SHIRT
1949,30,110.00,JAVA PROGRAMMING TEXTBOOK
5199,25,1.50,COOKIE
Anshu Tiwari, CSE, UCER
Example Processing a CSV File
• Uses the split method which puts strings separated
by a delimiter into an array
Anshu Tiwari, CSE, UCER
File: [Link]
SKU,Quantity,Price,Description
4039,50,0.99,SODA
9100,5,9.50,T-SHIRT
1949,30,110.00,JAVA PROGRAMMING TEXTBOOK
5199,25,1.50,COOKIE
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TransactionReader
{
public static void main(String[] args)
{
String fileName = "[Link]";
try
{
Scanner inputStream = new Scanner(new File(fileName));
// Read the header line
String line = [Link]();
double total = 0; // Total sales
// Read the rest of the file line by line
while ([Link]())
{
// Contains SKU,Quantity,Price,Description
line = [Link]();
// Turn the string into an array of strings
String[] ary = [Link](",");
// Extract each item
String SKU = ary[0];
int quantity = [Link](ary[1]);
double price = [Link](ary[2]);
String description = ary[3];
// Output item
[Link]("Sold %d of %s (SKU: %s) at $%1.2f each.\n",
quantity, description, SKU, price);
// Compute total
total += quantity * price;
}
[Link]("Total sales: $%1.2f\n",total);
[Link]( );
}
catch(FileNotFoundException e)
{
[Link]("Cannot find file " + fileName);
}
catch(IOException e)
{
[Link]("Problem with input from file " + fileName);
}
}
}
Basic Binary-File I/O
• Creating a Binary File
• Writing Primitive Values to a Binary File
• Writing Strings to a Binary File
• The Class EOFException
• Programming Example: Processing a File of Binary
Data
Anshu Tiwari, CSE, UCER
Creating a Binary File
• Stream class ObjectOutputStream allows files
which can store
• Values of primitive types
• Strings
• Other objects
Anshu Tiwari, CSE, UCER
Creating a Binary File
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class BinaryOutputDemo
{
public static void main (String [] args)
{
String fileName = "[Link]";
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream (new FileOutputStream (fileName));
Scanner keyboard = new Scanner ([Link]);
Anshu Tiwari, CSE, UCER
Creating a Binary File
[Link] ("Enter nonnegative integers.");
[Link] ("Place a negative number at the end.");
int anInteger;
do
{
anInteger = [Link] ();
[Link] (anInteger);
}
while (anInteger >= 0);
[Link] ("Numbers and sentinel value");
[Link] ("written to the file " + fileName);
[Link] ();
}
Anshu Tiwari, CSE, UCER
Creating a Binary File
catch (FileNotFoundException e)
{
[Link] ("Problem opening the file " + fileName);
}
catch (IOException e)
{
[Link] ("Problem with output to file " + fileName);
}
}
}
Anshu Tiwari, CSE, UCER
Writing Primitive Values to a Binary File
• Some methods in class ObjectOutputStream
Writing Primitive Values to a Binary File
Some methods in class ObjectOutputStream
Writing Primitive Values to a Binary File
Some methods in class ObjectOutputStream
Anshu Tiwari, CSE, UCER
Writing Strings to a Binary File
• Use method writeUTF
• Example
[Link]("Hi Mom");
• UTF stands for Unicode Text Format
• Uses a varying number of bytes to store different strings
• Depends on length of string
• Contrast to writeInt which uses same for each
Anshu Tiwari, CSE, UCER
Reading from a Binary File
• File must be opened as an
ObjectInputStream
• Read from binary file using methods which
correspond to write methods
• Integer written with writeInt will be read with
readInt
• Be careful to read same type as was written
Anshu Tiwari, CSE, UCER
Reading from a Binary File
Some methods of class ObjectInputStream
Reading from a Binary File
Some methods of class ObjectInputStream
Anshu Tiwari, CSE, UCER
Reading from a Binary File
Some methods of class ObjectInputStream
Anshu Tiwari, CSE, UCER
Reading from a Binary File
Some methods of class ObjectInputStream
Anshu Tiwari, CSE, UCER
Reading from a Binary File
Some methods of class ObjectInputStream
Anshu Tiwari, CSE, UCER
Reading from a Binary File
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class BinaryInputDemo
{
public static void main (String [] args)
{
String fileName = "[Link]";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
Anshu Tiwari, CSE, UCER
Reading from a Binary File
[Link] ("Reading the nonnegative integers");
[Link] ("in the file " + fileName);
int anInteger = [Link] ();
while (anInteger >= 0)
{
[Link] (anInteger);
anInteger = [Link] ();
}
[Link] ("End of reading from file.");
[Link] ();
}
catch (FileNotFoundException e)
{
[Link] ("Problem opening the file " + fileName);
}
Anshu Tiwari, CSE, UCER
Reading from a Binary File
catch (EOFException e)
{
[Link] ("Problem reading the file " + fileName);
[Link] ("Reached end of the file.");
}
catch (IOException e)
{
[Link] ("Problem eading the file " + fileName);
}
}
}
Anshu Tiwari, CSE, UCER
The Class EOFException
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class EOFExceptionDemo
{
public static void main (String [] args)
{
String fileName = "[Link]";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
Anshu Tiwari, CSE, UCER
The Class EOFException
[Link] ("Reading ALL the integers");
[Link] ("in the file " + fileName);
try
{
while (true)
{
int anInteger = [Link] ();
[Link] (anInteger);
}
}
catch (EOFException e)
{
[Link] ("End of reading from file.");
}
[Link] ();
}
Anshu Tiwari, CSE, UCER
The Class EOFException
catch (FileNotFoundException e)
{
[Link] ("Cannot find file " + fileName);
}
catch (IOException e)
{
[Link] ("Problem with input from file " + fileName);
}
}
}
Anshu Tiwari, CSE, UCER
Programming Example
• Processing a file of binary data
• Asks user for 2 file names
• Reads numbers in input file
• Doubles them
• Writes them to output file
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
• Consider the need to write/read objects other than
Strings
• Possible to write the individual instance variable values
• Then reconstruct the object when file is read
• A better way is provided by Java
• Object serialization – represent an object as a sequence of
bytes to be written/read
• Possible for any class implementing Serializable
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
• Interface Serializable is an empty interface
• No need to implement additional methods
• Tells Java to make the class serializable (class objects
convertible to sequence of bytes)
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
import [Link];
import [Link];
/**
Serialized class for data on endangered species.
*/
public class Species implements Serializable
{
private String name;
private int population;
private double growthRate;
public Species ()
{
name = null;
population = 0;
growthRate = 0;
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
public Species (String initialName, int initialPopulation,double initialGrowthRate)
{
name = initialName;
if (initialPopulation >= 0) population = initialPopulation;
else
{
[Link] ("ERROR: Negative population.");
[Link] (0);
}
growthRate = initialGrowthRate;
}
public String toString ()
{
return ("Name = " + name + "\n" +"Population = " + population + "\n" +
"Growth rate = " + growthRate + "%");
}
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
• Once we have a class that is specified as
Serializable we can write objects to a binary file
• Use method writeObject
• Read objects with method readObject();
• Also required to use typecast of the object
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
import [Link];
import [Link];
import [Link];
import [Link];
public class ClassObjectIODemo
{
public static void main (String [] args)
{
ObjectOutputStream outputStream = null;
String fileName = "[Link]";
try{
outputStream = new ObjectOutputStream (new FileOutputStream (fileName));
}
catch (IOException e) {
[Link] ("Error opening output file " + fileName + ".");
[Link] (0);
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
Species califCondor = new Species ("Calif. Condor", 27, 0.02);
Species blackRhino = new Species ("Black Rhino", 100, 1.0);
try
{
[Link] (califCondor);
[Link] (blackRhino);
[Link] ();
}
catch (IOException e)
{
[Link] ("Error writing to file " + fileName + ".");
[Link] (0);
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
[Link] ("Records sent to file " + fileName + ".");
[Link] ( "Now let's reopen the file and echo the records.");
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream ( new FileInputStream ("[Link]"));
}
catch (IOException e)
{
[Link] ("Error opening input file " + fileName + ".");
[Link] (0);
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
Species readOne = null, readTwo = null;
try {
readOne = (Species) [Link] ();
readTwo = (Species) [Link] ();
[Link] ();
}
catch (Exception e) {
[Link] ("Error reading from file " + fileName + ".");
[Link] (0);
}
[Link] ("The following were read\n" + "from the file " + fileName + ".");
[Link] (readOne);
[Link] ();
[Link] (readTwo);
[Link] ("End of program.");
}
}
Anshu Tiwari, CSE, UCER
Some Details of Serialization
• Requirements for a class to be serializable
• Implments interface Serializable
• Any instance variables of a class type are also objects of a
serializable class
• Class's direct superclass (if any) is either serializable or
defines a default constructor
Anshu Tiwari, CSE, UCER
Some Details of Serialization
• Effects of making a class serializable
• Affects how Java performs I/O with class objects
• Java assigns a serial number to each object of the class it
writes to the ObjectOutputStream
• If same object written to stream multiple times, only the
serial number written after first time
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
• Since an array is an object, possible to use
writeObject with entire array
• Similarly use readObject to read entire array
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ArrayIODemo
{
public static void main (String [] args)
{
Species [] oneArray = new Species [2];
oneArray [0] = new Species ("Calif. Condor", 27, 0.02);
oneArray [1] = new Species ("Black Rhino", 100, 1.0);
String fileName = "[Link]";
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream ( new FileOutputStream (fileName));
[Link] (oneArray);
[Link] ();
}
catch (IOException e)
{
[Link] ("Error writing to file " + fileName + ".");
[Link] (0);
}
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
[Link] ("Array written to file " +fileName + " and file is closed.");
[Link] ("Open the file for input and " + "echo the array.");
Species [] anotherArray = null;
try
{
ObjectInputStream inputStream =
new ObjectInputStream ( new FileInputStream (fileName));
anotherArray = (Species []) [Link] ();
[Link] ();
}
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
catch (Exception e)
{
[Link] ("Error reading file " + fileName + . );
[Link] (0);
}
[Link] ("The following were read from " + "the file " + fileName + ":");
for (int i = 0 ; i < [Link] ; i++)
{
[Link] (anotherArray [i]);
[Link] ();
}
[Link] ("End of program.");
}
}
Anshu Tiwari, CSE, UCER