Chapter 2-Java IO
Chapter 2-Java IO
Java Input/output
A stream
Source reads
Program
Writing to a stream
writes A stream
Program
Destination
Unit 1 (part 1 of 2): Java IO 6
Types of Streams
• Java defines two types of streams: byte based and
character based.
Byte Based
• Streams provide convenient way for handling input and output of 8-
bit bytes and are used for input/output of binary data.
• Files created by byte based streams are called binary files. These
files are easily read by the computer but not humans.
• Binary data are not very portable (platform dependent).
• On some systems an integer might be 16 bits, and on others it might
be 32 bits, so even if you know that a Macintosh binary file contains
integers, that still won't make it readable by Windows/Intel
programs.
11 13
Unit 1 (part 1 of 2): Java IO
Java IO and Streams
• Streams in JAVA are Objects.
• Having
2 types of streams (text / binary) and
2 directions (input / output)
• Results in 4 base-classes dealing with I/O:
1. InputStream: byte-input
2. OutputStream: byte-output
3. Reader: text-input
4. Writer: text-output
+read(): int Reads the next byte of data from the input stream. The value byte is returned as
an int value in the range 0 to 255. If no byte is available because the end of
the stream has been reached, the value –1 is returned.
+read(b: byte[]): int Reads up to b.length bytes into array b from the input stream and returns the
actual number of bytes read. Returns -1 at the end of the stream.
+read(b: byte[], off: int, Reads bytes from the input stream and stores into b[off], b[off+1], …,
len: int): int b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the
end of the stream.
+available(): int Returns the number of bytes that can be read from the input stream.
+close(): void Closes this input stream and releases any system resources associated with the
stream.
+skip(n: long): long Skips over and discards n bytes of data from this input stream. The actual
number of bytes skipped is returned.
+markSupported(): Tests if this input stream supports the mark and reset methods.
boolean
Marks the current position in this input stream.
+mark(readlimit: int):
Repositions this stream to the position at the time the mark method was last
void
called on this input stream.
+reset(): void
Unit 1 (part 1 of 2): Java IO 23
OutputStream
The value is a byte as an int type.
java.io.OutputStream
+write(int b): void Writes the specified byte to this output stream. The parameter b is an int valu
(byte)b is written to the output stream.
+write(b: byte[]): void Writes all the bytes in array b to the output stream.
+write(b: byte[], off: Writes b[off], b[off+1], …, b[off+len-1] into the output stream.
int, len: int): void
+close(): void Closes this input stream and releases any system resources associated with th
stream.
+flush(): void Flushes this output stream and forces any buffered output bytes to be written
ObjectOutputStream PrintStream
FileInputStream/FileOuptputStream is for
reading/writing bytes from/to files .
A java.io.FileNotFoundException would
occur if you attempt to create a FileInputStream with a
nonexistent file.
FileInputStream("SourceFile.txt"); ;
FileOutputStream out = new
FileOutputStream("TargetFile.txt“);
int c;
if (in != null) {
in.close();
}
if (out != null) {
out.close();
} Unit 1 (part 1 of 2): Java IO 29
}}
FilterInputStream/FilterOutputStream
FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream
ObjectOutputStream PrintStream
ObjectOutputStream PrintStream
InputStream java.io.DataInput
FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream
ObjectOutputStream PrintStream
// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize)
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStreamr out, int
bufferSize)
FileReader(File file)
Constructs a FileReader object given a File object.
FileReader(String fileName)
Constructs a FileReader object given a file name.
int c;
while ((c = inputStream.read())!= -1) {
outputStream.write(c);
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
Unit 1 (part 1 of 2): Java IO 49
Reading/Writing to a Text File…
• Other classes which could be used for writing to a
text file are: all classes are subclasses of Writer class:
BufferedWritter, CharArrayWritter, PipedWritter,
StringWritter, PrintWritter.
• BufferedReader, LineNumberReader
• CharArrayReader
• InputStreamReader, FileReader
• FilterReader
• PushbackReader
• PipedReader
• StringReader
int i = 55;
p.print( i );
Unit 1 (part 1 of 2): Java IO 55
PrintWritter
• For real world programs the recommended way of writing
to the console is PrintWriter class.
• To create the object we use the following constructor.
PrintWriter p = new PrintWriter(System.out);
System.out
bytes
Console PrintWriter
Data
Program
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
Unit 1 (part 1 of 2): Java IO 57
Exercise
• Write a method that takes the file name and extracts
each line of the files and displays the line to a
console.
System.in
single byte
Keyboard InputStreamReader
ClassNotFoundException
• This method retrieves the next Object out of the stream
and deserializes it.
• The return value is Object, so you will need to cast it to
its appropriate data type.
• To demonstrate how serialization works in Java, suppose
that we have the following Employee class, which
implements the Serializable interface.
Unit 1 (part 1 of 2): Java IO 72
Java – Serialization…Example
• public class Employee implements java.io.Serializable {
public String name;
public String address;
public int transient SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name+ " " +
address); }}
• Notice that for a class to be serialized successfully, two
conditions must be met:
• The class must implement the java.io.Serializable interface.
• All of the fields in the class must be serializable. If a field is not
serializable, it must be marked transient.
Unit 1 (part 1 of 2): Java IO 73
Serialization - Serializing an Object
• The ObjectOutputStream class is used to serialize an Object. The following
SerializeDemo program instantiates an Employee object and serializes it to a file.
• When the program is done executing, a file named employee.ser is created. The
program does not generate any output, but study the code and try to determine what
the program is doing.
• Note: When serializing an object to a file, the standard convention in Java is to give the
file a .ser extension.
import java.io.*;
public class SerializeDemo{
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
Output
Deserialized Employee...
Name: Reyan Ali, Address:Phokka Kuan, Ambehta Peer, SSN: 0,
Unit 1 (part 1 of 2): Java IO 77
Number:101
Serialization - DeSerializing an Object…
• Here are following important points to be noted:
• The try/catch block tries to catch a
ClassNotFoundException, which is declared by the
readObject() method. For a JVM to be able to deserialize
an object, it must be able to find the bytecode for the
class. If the JVM can't find a class during the
deserialization of an object, it throws a
ClassNotFoundException.
• Notice that the return value of readObject() is cast to an
Employee reference.
• The value of the SSN field was 11122333 when the
object was serialized, but because the field is transient,
this value was not sent to the output stream. The SSN
field of the deserialized Employee object is 0.
Unit 1 (part 1 of 2): Java IO 78
Important Points about Serialization
• If you declare a variable as transient it will not be saved
during serialization.
• Serializable interface is an empty interface.
• If a class is serializable, then all the subclasses of this
super class are implicitly serializable even if they don’t
explicitly implement the Serializable interface.
• If you are serializing an array or collection, each of its
elements must be serializable.
• static variables are not saved as part of serialization.