Transcript I/O streams

Streams
Overview

I/O streams

Opening a text file for reading

Reading a text file

Closing a stream

Reading numbers from a text file

Writing or appending to a text file
1
I/O streams
Binary and Text files
 Binary file: A file whose contents must be handled as a
sequence of binary digits.
 Text file: A file whose contents are to be handled as a
sequence of characters.
Why use files for I/O?
1. Files provide permanent storage of data.
2. Files provide a convenient way to deal with large
quantities of data.
I/O streams
 In Java, I/O is handled by streams.
 An input stream is an object that takes data from a source and
delivers it to a program.
 An output stream is an object that takes data from a program
and delivers data it to a destination.
 Java has the following standard streams: System.in,
System.out, and System.err. System.in is connected to the
keyboard. System.out and System.err are connected to the
screen.
2
Opening a text file for reading
You create a stream of the class BufferedReader and connect it
to a text file for reading as follows:
BufferedReader streamName = new BufferedReader
(new FileReader(filename));
Where filename is a File object or a constant string or a String
variable containing the name or the full path of the file to be
read.
Example of valid filenames:
1. “myinput.txt”
2. “C:\\homework\\StudentTest.java”
3. “C:/homework/StudentTest.java”
4.
fileObject = new File(“C:/homework/StudentTest.java”);
BufferedReader streamName = new BufferedReader
(new FileReader(fileObject));
Note:
The full path to a file can be read from the keyboard; in that
case you must not type any of the backslashes twice.
3
Opening a text file for reading (Cont’d)

The class BufferedReader has no constructor that takes a file
name or a File object as its argument.

The class FileReader will accept a file name (or an object of
the class File) as a constructor argument and produce a stream
that is a Reader.

The constructor for BufferedReader will accept a Reader as
an argument.

Both BufferedReader and FileReader classes belong to the
java.io package.

The FileReader constructor throws a FileNotFoundException,
if the text file to be opened for reading does not exist:
FileReader(String filename) throws FileNotFoundException

The FileNotFoundException is a subclass of the class
IOException, so any catch-block that catches exceptions of
the class IOException will also catch exceptions of the class
FileNotFoundException.
4
Reading a text file
After a text file has been opened for reading you can use the
methods readLine( ) or read( ) of the stream to read from the file:
1.
public String readLine( ) throws IOException
This method reads a line of input from the input stream and returns
that line as a string. If an attempt is made to read beyond the end
of file, null is returned.
2. public int read( ) throws IOException
This method reads a single character from the input stream and
returns that character as an integer value. To obtain the character,
you must perform a type cast on the value returned. For example:
char next = (char) inputStream.read( )
If an attempt is made to read beyond the end of the file, -1 is
returned.
Note: The end of file may be detected by using the boolean method
ready( ) of an input stream. The method returns false if the end of
file is reached; otherwise it returns true:
...
String input;
while( inputStream.ready( ) )
{
input = inputStream.readLine( );
...
}
5
Closing a stream
When your program has finished writing to or reading from a
file, it should close the stream connected to that file by calling
the close( ) method of the stream:
streamName.close( )
The method close( ) is defined as:
public void close( ) throws IOException
» When you close a file, the system releases any resources
used to connect the stream to the file.
» If your program does not close a file before the program
ends, then the system will close it for you.
6
Example1 (File display)

Example: The following program displays the contents of the file
myinput.txt on the screen by reading one character at a time:
import java.io.*;
public class ShowFile
{
public static void main(String[ ] args) throws IOException
{
int input;
BufferedReader fin = null;
try
{
fin = new BufferedReader(new FileReader("myinput.txt"));
input = fin.read( );
while( input != -1)
{
System.out.print((char) input);
input = fin.read( );
}
fin.close( );
}
catch(FileNotFoundException e)
{
System.out.println("Error - File myinput.txt not found");
}
}
7
Reading numbers from a text file


The BufferedReader class has no methods that can read a
number.
To read a number from a text file, use the parse method of an
appropriate Wrapper class.
Example: The following program reads float numbers from a file. It
displays the numbers on the screen, computes their average, and
displays that average on the screen:
import java.io.*;
public class Average
{
public static void main(String[ ] args)
{
try{
BufferedReader fin = new
BufferedReader(new FileReader("numbers.txt"));
String inputLine;
double grade, sum = 0.0;
int count = 0;
inputLine = fin.readLine( );
while( inputLine != null)
{
grade = Double.parseDouble(inputLine);
sum += grade;
count++;
System.out.println(grade);
inputLine = fin.readLine( );
}

8
Reading numbers from a text file (Cont’d)
if(count = = 0)
System.err.println("Error - no grades were read");
else
System.out.println("\nThe average is " + sum / count);
fin.close( );
}
catch(FileNotFoundException e)
{
System.err.println("Error - File myinput.txt not found");
}
catch(IOException e)
{
System.err.println("Error - An I/O error occured");
}
catch(NumberFormatException e)
{
System.err.println("Error - An invalid float number read");
}
}
}
9
Writing or appending to a text file
• A text file is opened for writing, either one character at a
time or one line at a time, by a statement of the form:
PrintWriter streamName = new
PrintWriter(new FileWriter(filename));
Any preexisting file by the same name is destroyed. If the
file does not exist it is created.
•A text file is opened for appending, either one character at
a time or one line at a time, by a statement of the form:
PrintWriter streamName = new
PrintWriter(new FileWriter(filename , true));
Any preexisting file by the same name is not destroyed.If
the file does not exist it is created.
•Both PrintWriter and FileWriter classes belong to java.io
package.
 The PrintWriter class has methods print( ) and println( )
that print either one character or one line at a time.
•Each constructor
IOException:
of
the
FileWriter
can
throw
FileWriter(String filename) throws IOException
FileWriter(String filename , boolean appendFlag)
throws IOException
10
an
Writing or appending to a text file (Cont’d)
• The class FileWriter has
constructors that takes a
filename or a File object as its argument; however this
class does not have methods to write one line at a time.
• The class PrintWriter does not have a constructor that
takes a filename or an object of the class File as its
argument; however it has a constructor that takes a
FileWriter object as argument. It also has a method to write
one line at a time.
 So we use the class FileWriter together with the class
PrintWriter.
Example: The following program appends a message to the
file datafile.txt
import java.io.*;
public class FileAppend
{ public static void main(String[ ] args) throws IOException
{ String message = "Java is platform independent";
PrintWriter outputStream =
new PrintWriter(new FileWriter("datafile.txt", true));
outputStream.println(message);
outputStream.close( );
}
}
11
Example (Copying a text file)
Example: The following program copies one file to another;
but it converts every lowercase character to uppercase.
import java.io.*;
public class FileCopy{
public static void main(String[ ] args) {
int input;
BufferedReader fin;
PrintWriter fout ;
try {
fin = new BufferedReader(new FileReader("myinput.txt"));
}
catch(FileNotFoundException e){
System.out.println("Input File not found");
System.exit(1); }
try{
fout = new PrintWriter(new FileWriter("myoutfile.txt"));
}
catch(IOException e){
System.out.println("Error opening output file");
System.exit(1); }
12
Example (Copying a text file) (Cont’d)
try {
input = fin.read( );
while(input != -1) {
fout.print(input);
input = fin.read( );
}
}
catch(IOException e) {
System.out.println("Error in reading the file myinput.txt");
}
try{
fin.close( );
fout.close( );
}
catch(IOException e) {
System.out.println("Error in closing a file");
}
System.out.println("File copied successfully");
}
}
13