Escolar Documentos
Profissional Documentos
Cultura Documentos
JAVA Programming
Lecture 7
byte stream
byte stream
Java distinguishes between byte streams and
character streams
In Java, a character is represented by a 2-
byte Unicode character (www.unicode.org)
Reader object
character stream
Writer object
character stream
Finally Java uses the concept of a data stream to
read and write useful data such as integers and
doubles (as opposed to just bytes and characters)
Java uses a mechanism called layering to attach
these different types of streams together
For example we can attach an input stream to a
file and then attach a data input stream to the
file input stream so we can read a file of
integers. (See later!)
The java.io package contains all of the classes for
input/output and streams
Its all quite complex because of its huge
flexibility
Its even worse than that because before we can use
streams we need to know about exceptions!!
Exception handling
All Java programs which deal with files and/or
streams must include exception handling
Exceptions are error conditions encountered in
executing class methods
Attempting to read past an end of file
Divide by zero
etc
Normal error handling (in C) would return
an error code (eg. 1)
class myClass
{
.
.
public int readFile(.)
{
do
{
if (!end_of_file)
// read the file
else
return 1;
} while not_end_of_file
return number_of_bytes_read;
}
}
This is a simple sometimes effective method but:
Sometimes not possible to return a valid error
code.
Not object oriented! No information about the
error is contained in the error code
Application code gets polluted with error
checking code
It would be nice to have all of the error
handling in one place
The method might not be able to return
normally from the error.
An example would be if a resource the
method was accessing was not available
In Java, if an error occurs in a method, an
Exception object is thrown by the method
Any method that calls the first method
error codes
class myClass
{
.
.
public int myMethod
{
.
.
anObject.throwMethod(); // can throw an exception
.
return value; // normal return point
{
// Exception handler code
// Control passed to here if
// exception thrown
}
}
}
Alternatively, the method calling throwMethod()
doesnt want to deal with the exception, so it
throws it on to the caller of myClass.myMethod()
to worry about
The exception can be thrown along a chain of
method calls until eventually one of the
methods decides to deal with it
It cant be ignored at the very least the outer
method call must deal with it!
class anotherClass
{
.
public int anotherMethod
{
.
.
myObject. myMethod(); // throws on the exception
.
.
return value; // normal return point
{
// Exception handler code
// Control passed to here if
// exception thrown
}
}
}
Throwing exceptions
A method must advertise the fact that it is going to
throw an exception of a specific type
For example some problem with I/O
Exception
IOException RuntimeException
Creating exception classes
It is easy to create our own exceptions by
extending an existing exception class
NumberFormatException exception
Notice how there may be several catch()
clauses to catch multiple exceptions
The stream class hierarchy
Java has 2 abstract base classes, InputStream and
OutputStream for representing input and output
stream objects
InputStream and OutputStream are base classes
of a large hierarchy (more than 60!) of stream
classes
For example, classes FileInputStream and
FileOutputStream allow input and output streams
to be attached to files
Java also has 2 other abstract base classes, Reader
and Writer for handling Unicode character based
I/O
InputStream
FileInputStream
OutputStream
FileOutputStream
Reader
Writer
myFile.dat
FileInputStream has a method read() which
returns the byte read and 1 if it reaches the end of
the input stream
public int read() throws IOException
Formatted file
Example
The following program writes integers and
doubles to a file and then reads them back
Uses DataInputStream.readInt() and
DataInputStream.readDouble() for
reading
Uses DataOutputStream.writeInt() and
DataOutputStream.writeDouble() for
writing
Catches an end of file exception
public class FormattedFileTest
{
public static void main(String[] args)
{
String fname=args[0];
try
{
FileOutputStream fout=new FileOutputStream(fname);
DataOutputStream dout=new DataOutputStream(fout);
for (int i=0; i<100; i++)
{ dout.writeInt(i); dout.writeDouble(i*0.5); }
}
catch (IOException e) { System.out.println("i/o problem!");}
try
{
FileInputStream fin=new FileInputStream(fname);
DataInputStream din=new DataInputStream(fin);
for (int j=0; j<150; j++)
{ int i=din.readInt(); double d=din.readDouble(); }
}
catch (EOFException e) { System.out.println("EOF!");}
catch (IOException e) { System.out.println("i/o problem!");}
}
}
Layering streams
reading/writing gzip files
A Java program can read/write gzipped (and
zipped) compressed files using stream
layering
Classes GZIPInputStream and
GZIPOutputStream enable i/o to be
performed on gzipped files
Similarly, classes ZipInputStream and
ZipOutputStream allow i/o on zipped files
We can add a gzipped input stream to our
previous example enabling us to read
formatted data from a gzipped file!
gzipped
DataInputStream GZIPInputStream
input stream
FileInputStream
Zip file
The following code segment shows how the
file created in the previous example can be
read after gzipping
A file is gzipped using the UNIX
command gzip filename
.
try
{
FileInputStream fin=new FileInputStream(fname);
GZIPInputStream gin=new GZIPInputStream(fin);
DataInputStream din=new DataInputStream(gin);
for (int j=0; j<150; j++)
{ int i=din.readInt(); double d=din.readDouble(); }
}
catch (EOFException e) { System.out.println("EOF!");}
catch (IOException e) { System.out.println("i/o problem!");}
.
.
Reading and writing text files
All of our classes so far have been for binary files
Data is stored in files as bytes which is efficient
but not humanly readable
A text file consists of information stored in
humanly readable form
For example the number 150 would be stored
as 1 5 0 instead of the binary representation
of 150 (10010110)
Java has a number of classes (descended from the
abstract Reader and Writer classes) for handling
text i/o
Outputting to a text file
This can easily be done with the PrintStream
class
Both text and numeric data can be output
using the print() and println() methods
Contains overloaded methods print(char
c), print(int i), print(double d), etc
Uses a filter class (FilterOutputStream) to
convert from Unicode to readable characters
The following program segment outputs string and
numeric text to a text file
Be clear about the difference between this and
.
System.out.println(Hello World!);
System.out.println(x= + x);
.
Console based input is more difficult
A class Console has been written by the
authors of the Core Java book providing
convenient input methods
readLine() returns a string
import Console.*;
class ConsoleTest
{
static void main(String args[])
{
int i=Console.readInt("Input an integer: ");
double d=Console.readDouble("Input a double: ");
System.out.println("Values entered= "+ i + " " + d);
}
}
And finally
Java handling of files and streams is extensive
We have only just scratched the surface!