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 java.io
• 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 java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileOutputDemo
{
public static void main (String [] args)
{
String fileName = "out.txt"; //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)
{
System.out.println ("Error opening the file " + fileName);
System.exit (0);
}
System.out.println ("Enter three lines of text:");
Scanner keyboard = new Scanner (System.in);
for (int count = 1 ; count <= 3 ; count++)
{
String line = keyboard.nextLine ();
outputStream.println (count + " " + line);
}
outputStream.close ();
System.out.println ("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 java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo
{
public static void main (String [] args)
{
String fileName = "out.txt";
Scanner inputStream = null;
System.out.println ("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)
{
System.out.println ("Error opening the file " +fileName);
System.exit (0);
}
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
}
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 ("treasure.txt")
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 java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo2
{
public static void main (String [] args)
{
System.out.print ("Enter file name: ");
Scanner keyboard = new Scanner (System.in);
String fileName = keyboard.next ();
Scanner inputStream = null;
System.out.println ("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)
{
System.out.println ("Error opening the file " +fileName ");
System.exit (0);
}
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
}
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: Transactions.txt
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 java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class TransactionReader
{
public static void main(String[] args)
{
String fileName = "Transactions.txt";
try
{
Scanner inputStream = new Scanner(new File(fileName));
// Read the header line
String line = inputStream.nextLine();
double total = 0; // Total sales
// Read the rest of the file line by line
while (inputStream.hasNextLine())
{
// Contains SKU,Quantity,Price,Description
line = inputStream.nextLine();
// Turn the string into an array of strings
String[] ary = line.split(",");
// Extract each item
String SKU = ary[0];
int quantity = Integer.parseInt(ary[1]);
double price = Double.parseDouble(ary[2]);
String description = ary[3];
// Output item
System.out.printf("Sold %d of %s (SKU: %s) at $%1.2f each.\n",
quantity, description, SKU, price);
// Compute total
total += quantity * price;
}
System.out.printf("Total sales: $%1.2f\n",total);
inputStream.close( );
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch(IOException e)
{
System.out.println("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 java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryOutputDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream (new FileOutputStream (fileName));
Scanner keyboard = new Scanner (System.in);
Anshu Tiwari, CSE, UCER
Creating a Binary File
System.out.println ("Enter nonnegative integers.");
System.out.println ("Place a negative number at the end.");
int anInteger;
do
{
anInteger = keyboard.nextInt ();
outputStream.writeInt (anInteger);
}
while (anInteger >= 0);
System.out.println ("Numbers and sentinel value");
System.out.println ("written to the file " + fileName);
outputStream.close ();
}
Anshu Tiwari, CSE, UCER
Creating a Binary File
catch (FileNotFoundException e)
{
System.out.println ("Problem opening the file " + fileName);
}
catch (IOException e)
{
System.out.println ("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
outputStream.writeUTF("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 java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryInputDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
Anshu Tiwari, CSE, UCER
Reading from a Binary File
System.out.println ("Reading the nonnegative integers");
System.out.println ("in the file " + fileName);
int anInteger = inputStream.readInt ();
while (anInteger >= 0)
{
System.out.println (anInteger);
anInteger = inputStream.readInt ();
}
System.out.println ("End of reading from file.");
inputStream.close ();
}
catch (FileNotFoundException e)
{
System.out.println ("Problem opening the file " + fileName);
}
Anshu Tiwari, CSE, UCER
Reading from a Binary File
catch (EOFException e)
{
System.out.println ("Problem reading the file " + fileName);
System.out.println ("Reached end of the file.");
}
catch (IOException e)
{
System.out.println ("Problem eading the file " + fileName);
}
}
}
Anshu Tiwari, CSE, UCER
The Class EOFException
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class EOFExceptionDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
Anshu Tiwari, CSE, UCER
The Class EOFException
System.out.println ("Reading ALL the integers");
System.out.println ("in the file " + fileName);
try
{
while (true)
{
int anInteger = inputStream.readInt ();
System.out.println (anInteger);
}
}
catch (EOFException e)
{
System.out.println ("End of reading from file.");
}
inputStream.close ();
}
Anshu Tiwari, CSE, UCER
The Class EOFException
catch (FileNotFoundException e)
{
System.out.println ("Cannot find file " + fileName);
}
catch (IOException e)
{
System.out.println ("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 java.io.Serializable;
import java.util.Scanner;
/**
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
{
System.out.println ("ERROR: Negative population.");
System.exit (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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ClassObjectIODemo
{
public static void main (String [] args)
{
ObjectOutputStream outputStream = null;
String fileName = "species.records";
try{
outputStream = new ObjectOutputStream (new FileOutputStream (fileName));
}
catch (IOException e) {
System.out.println ("Error opening output file " + fileName + ".");
System.exit (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
{
outputStream.writeObject (califCondor);
outputStream.writeObject (blackRhino);
outputStream.close ();
}
catch (IOException e)
{
System.out.println ("Error writing to file " + fileName + ".");
System.exit (0);
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
System.out.println ("Records sent to file " + fileName + ".");
System.out.println ( "Now let's reopen the file and echo the records.");
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream ( new FileInputStream ("species.records"));
}
catch (IOException e)
{
System.out.println ("Error opening input file " + fileName + ".");
System.exit (0);
}
Anshu Tiwari, CSE, UCER
Binary-File I/O with Class Objects
Species readOne = null, readTwo = null;
try {
readOne = (Species) inputStream.readObject ();
readTwo = (Species) inputStream.readObject ();
inputStream.close ();
}
catch (Exception e) {
System.out.println ("Error reading from file " + fileName + ".");
System.exit (0);
}
System.out.println ("The following were read\n" + "from the file " + fileName + ".");
System.out.println (readOne);
System.out.println ();
System.out.println (readTwo);
System.out.println ("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 java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
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 = "array.dat";
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream ( new FileOutputStream (fileName));
outputStream.writeObject (oneArray);
outputStream.close ();
}
catch (IOException e)
{
System.out.println ("Error writing to file " + fileName + ".");
System.exit (0);
}
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
System.out.println ("Array written to file " +fileName + " and file is closed.");
System.out.println ("Open the file for input and " + "echo the array.");
Species [] anotherArray = null;
try
{
ObjectInputStream inputStream =
new ObjectInputStream ( new FileInputStream (fileName));
anotherArray = (Species []) inputStream.readObject ();
inputStream.close ();
}
Anshu Tiwari, CSE, UCER
Array Objects in Binary Files
catch (Exception e)
{
System.out.println ("Error reading file " + fileName + . );
System.exit (0);
}
System.out.println ("The following were read from " + "the file " + fileName + ":");
for (int i = 0 ; i < anotherArray.length ; i++)
{
System.out.println (anotherArray [i]);
System.out.println ();
}
System.out.println ("End of program.");
}
}
Anshu Tiwari, CSE, UCER