Java IO

java.io Package The java.io package provides classes to access file randomly and sequential.Text and data file can be read and written to.
There are classes and interfaces used to read and write primitive and serialization of objects to file and rebuild the object.
From the beginning, Java has been network aware.
Stream A stream is an ordered sequence of bytes that have a source or a destination.
All stream classes work sequentially.
Exam Tip These are the top-level IO classes. Knowing them helps to easily understand the Java IO class hierarchies.
Exam Tip InputStream and OutputStream,FilterInputStream and FilterOutputStream,

FileInputStream and FileOutputStream

RandomAccessFile

Primary Interfaces and classes for IO operations InputStream OutputStream FilterInputStream FilterOutputStream DataInputDataOutput
InputStream / OutputStream InputStream and OutputStream are abstract classes at the base of the hierarchy of Java classes representing 8-bit byte streams.
Abstract class providing basic method for reading, writing and closing a stream. Base class for the filter Input/Output streams and other classes.
Both these classes ascend from the Object class.
InputStream Class extending InputStream reads the next byte of data from a source.
read()read(byte) Basic reading methods.
skip() Skips a byte.
available() Test if any bytes are available to be read.
close() Close the stream.
OutputStream Class extending OutputStream write the a single byte of data.
write()write(byte) Basic writing methods.
flush() Writes any bytes in a buffer to the stream.
close() Close the stream.
Exam Tip Both the InputStream and OutputStream have the close() method.
Exam Tip No open() method is part of the Input/Output stream.
Stream Filters InputStream and OutputStream manipulate raw bytes. Most program use primitive data types. Filters connect to the InputStream and OutputStream perform some transformation on the data.
FilterInputStream and FilterOutputStream FilterInputStream and FilterOutputStream are subclasses of the InputStream and OutputStream. They are the base class of many other filter streams.
When using a filter stream object, an instance of the InputStream or OutputStream are passed to its constructor as an argument respectively. 

This process is called chaining.

Chaining A InputStream and OutputStream, or FilterInputStream and FilterOutputStream can be chained to a FilterInputStream and FilterOutputStream respectively.
Exam Tip An InputStream is the argument for a FilterInputStream.An OutputStream is the argument for a FilterOutputStream.
Exam Tip A File instance can not be passed to a FileInputStream.
FileInputStream fls = new FileInputStream(“mydata.bin”);DataInputStream ds = DataInputStream( fls );

d = ds.readDouble() //Read a double data from the stream

 

The DataInputStream stream filter chains the FileInputStream to itself. FileInputStream extends the InputStream.

The constructor of the filter stream can also accept another filter stream.
DataInput and DataOutput Interface These two interfaces provide methods for reading or writing all of the Java primitive types from reading/writing bytes of a binary stream respectively.
big-endian Java format for writing integer primitives is “big-endian.” The most significant bytes is written first.
Array of bytes can also be read and written by methods of these interfaces.
As well String objects and UTF-8 encoded character stream format.
DataInput Methods boolean readBoolean()byte readByte()

char readChar()

double readDouble()

DataOutput Methods void write(byte)void write(int)

void writeBoolean(boolean)

void writeByte(int)

void writeChar(int)

void writeDouble(double)

..

Direct subclasses of InputSream and OutputStream InputStream SubClasses: 

SequenceInputStream

StringBufferInputStream

ByteArrayInputStream

PipedInputStream

FileInputStream

OutputStream SubClasses: 

 

 

ByteArrayOutputStream

PipedOutputStream

FileOutputStream

FileInputStream Opens a file for reading using a file name or the File object. They implement the InputStream.
File f = new File(“hello.txt”);FileInputStream fi = new FileInputStream(f);

fi.close();

File f = new File(“hello.txt”);FileOutputStream fo = new FileOutputStream(f);

fo.close();

FileOutputStream Opens a file, or creates a new file for writing. In general the file is written over. They implement the OutputStream.
Exam Tip FileOutputStream creates a file.
BytesArrayInputStream Reads a byte array as if it were a file.
BytesArrayOutputStream An arbitrary sequence of data is written to a memory buffer.
SequenceInputStream This class enables the reading from a sequence of files. It reads the first file and proceeds until it comes to the end.
StringBufferInputStream This class enables the reading from a StringBuffer as you would a file.
PipedInputStream/ PipedOutputStream These classes allow the association of an input file with an output file or vice versa.
Direct subclasses of FilterInputSream and FilterOutputStream FilterInputStream SubClasses: 

LineNumberInputStream

BufferedInputStream

DataInputStream

PushbackInputStream

FilterOuttStream SubClasses: 

 

BufferedOutputSream

DataOutputStream

PrintStream

Exam Tip How to create a filter stream chain will be on the exam.
Buffered Stream InputStream can read a data, but cannot back it up. Reading a byte at a time is inefficient.
BufferedInputStream BufferedInputStream reads block of bytes into a buffer and supplies as output to a source. It supports mark, reset.
void mark(int) Marks the stream. Used like a book marker to back into the stream position.
void reset() Resets the stream operations.
Here are some buffered classes of java.io
BufferedOutputStream Bytes written to this stream are stored in a buffer until the buffer is full or flush is called.
Closing the stream flushes the stream automatically.
The size of the buffer is 512 bytes.
It does not supports mark, reset.
PrintStream Outputs the stream of bytes as 8-bit in the default encoding of the operating system. It outputs text representation of most primitives.
A PrintStream traps all IOExceptions and sets an internal flag when one occurs.
System.out The default output stream is a PrintStream.
The PrintStream constructor has been deprecated since the stream does not handle 16-bit character processing.
PrintWriter and PrintStream are to be used in Java 2.0
LineNumberInputStream This class keeps track of line number that is currently being read.
PushbackInputStream Reads a byte into a buffer and allows the “return” of the byte as unread. Can unread a single byte.
java.io.File It navigates the file system.
The File class extends the Object class.
The File class manipulates file systems in an operating-system-independent fashion.
The File class can delete and rename files and create directories.
A static variable separatorChar contains platform-independent path seperators. Backslash “” for DOS, window and foward slash “/” for Unix.
File(File parent, String path)File(String path)

File(String parent, String path)

The file may contain a directory, filename or combination. Path may contain an abstract path name. Path can be current user directory or absolute.
An array of files and subdirectory can be returned by File.All methods of File class may throw a SecurityException if program does not permission to access files. Example Applets.
File start = new File(“c:java”);File[] grp start.listFiles();
File object methods
Methods boolean exist() Returns true if the directory or file exists.
boolean isDirectory() Returns true if the File represents a directory.
boolean isFile() Returns true if File represents a normal file.
boolean canRead() Can a program read a file.
boolean canWrite() Can a program write a file.
long length() Returns the length of the file. The length position represent the last character in the file.
long lastModified() Returns the last modified data of the file.
boolean delete() Returns true if a program deleted file or directory.
boolean mkdir(File) Returns true if a directory was created.
public String getParent() Returns the parent directory
public String getPath() Returns the directory structure for this File object.
public String getParent() Returns the name of a file.
public String getAbsolutePath() Returns the absolute path of the file if the File object represent an absolute path.
java.io.RandomAccesFile RandomAccesFile class can read and write data to any part of file instead of the normal sequential means.
It is not a subclass of the InputStream and OutputStream. But is a subclass of the Object class.
It implements the DataInput and DataOutput interfaces. Java primitives and String Objects can be used.
Unlike other streams who must read from the beginning of the stream. RandomAccessFile can access a file at any location.
The RandomAccessFile has a file pointer that determines where the next read or write operation occurs.
On opening the file the pointer is at 0, the beginning of the file.
length() The length position represent the last character in the file. length()-1 positions the pointer before the last character.
seek(long) method Positions the file pointer at a specified location in the file.
RandomAccessFile(File f, String mode)RandomAccessFile(String file, String mode)
The mode for the RandomAccessFile are:r – Read only.

rw – Reading and writing.

Exam Tip There is no write mode for the RandomAccessFile.
Exam Tip Since the RandomAccesFile does not extend the Input/Output Stream base class they can not be chained.
There are three classes that implement the DataInput and DataOutput Interface: DataInputStream, DataOutputStream and RandomAccessFile.
DataInputStream It manipulates stream of bytes from the FileInputStream to read primitive data types.
chaining An input/output stream are chained to the input/output stream filters.
FileInputStream fls = new FileInputStream(“mydata.bin”);DataInputStream ds = DataInputStream( fls );

d = ds.readDouble() //Read a double data from the stream

DataOutputStream It manipulates stream of bytes from the FileOutputStream to write primitive data types.
FileOutputStream fls = new FileOutputStream(“mydata.bin”);BufferedOutputStream bos = new BufferedOutputStream(fls, 4096);

DataOutputStream dos = DataOutputStream( bos );

dos.flush(); //flushes the buffered sream

dos.close();

A file output stream is chained to a buffered stream, data is buffered and written to data output stream.
Exam Tip The File class does not have the no argument constructor.
Exam Tip The File class does not create files.
Exam Tip RandomAccesFile and FileOutputStream create files.
Streams and Characters Characters in Java are 16-bit Unicode data elements.
ASII ASCII code are 7-bit data. When java uses it they are transformed to 16-bit by adding an all-zero high byte. When a PrintStream uses it, the high bytes are dropped.
UTF-8 Unicode Text Form (UTF??) bridges between the world of 7-bit ASCII to 16-bit Unicode. It uses these rules, if the higher byte value is zero, it is an ASCII character. Else, the high byte is 1 and treated as a 16-bit character.
The UTF-8 characters between ‘u0020’ and ‘u007F’ are ASCII characters
DataInput / DataOutput The DataInput and DataOutput interface have these methods respectively:
String readUTF() Reads a 2 bytes and interprets it into a String
String writeUTF() Writes a 2 bytes unsigned integer.
Reader / Writer Classes The java.io.Reader and java.io.Writer classes provide are abstract classes for reading and writing codes besides Unicode.
Manipulates characters instead of bytes.
Reader and Writer classes take into account locale information provided by the operating system.
Here are classes implementing a Reader and Writer class. They all use the default character encoding.
BufferedReader Reads ahead a character input stream.
BufferedWriter Stores character in a buffer and writes the entire buffer when full, or when flush() method is called.
CharArrayReader An array of character, char, can be turned into a character stream.
CharArrayWriter Writes an array of characters.
FileReader Reads character files. It is an InputStreamReader combined with a FileInputStream.
FileWrite Writes character data. It is an OutputStreamWriter combined with a FileOutputStream.
InputStreamReader Bridges byte and character streams.
OutputStreamWriter Writes characters to an OutputStream of bytes.
PrintWriter This is the Writer derived analogous to the PrintStream class.
LineNumberReader Provides a buffer and counts lines as it reads a stream. Can provide the line number of the present position in the stream.
FileDescriptor FileDescriptor provides another way of creating an output stream. It can be used to create another stream from an existing stream.
The FileDescriptor represents an already opened file.
boolean valid() The FileDescriptor has only one method, valid(), which returns true if the it represent exist.
getFD() A FileDescriptor can be attained from the FileOutputStream or RandomAccessFile getFD() method.
Stream and URLs From the beginning Java used the HTTP protocol to communicate on the World Wide Web (WWW).
URL URL represent the address of a resource on the WWW.
It contains the host computer, protocol and resource information.
Applets and URL An applet can use the URL object to get at the URL information.
getDocumentBase() Return the URL for the web page the applet is embedded.
getCodeBase() Return the URL for the directory on the server that the applet class file came from.
Both these maybe different from the CODEBASE attribute specified in the APPLET tag.
Serialization Object serialization allows an object to be permanently, persistence, written to a file or transmitted over a network to another Java program.
For a class to serialized an object it must implement the java.io.Serializable interface.
The serialization process takes care of writing all of the linked objects and also keeps track of all objects that have been written so that no duplication occurs.
ObjectInput and Objectoutput ObjectInput and ObjectOutput interfaces allow the reading and writing of objects. They extend the DataInput and DataOutput interface.
ObjectInputStream ObjectInputStream extends the InputStream and implements the ObjectInput interface.
FileInputStream f = new FileInputStream(“object.bin”);ObjectInputStream is = ObjectInputStream( f );

Striog text = (String) (is.readObject());

is.close();

ObjectOutputStream ObjectOutputStream extends the OutputStream and implements the ObjectOutput interface.
FileOutputStream f = new FileOutputStream(“object.bin”);ObjectOutputStream os = ObjectOutputStream( f );

os.writeObject(“message in an object”);

os.close()

If a class implements the Serializable interface, then its public and protected instance variables can be read from and written to the stream automatically when the ObjectInputStream and ObjectOutputStream is used.
Exam Tip Private data can not be written to the stream for serialized classes.
If an instance variable refers to another object, that object will also be read or written recursively.
Exam Tip If a reference object does not implement the Serializable interface an NotSerializableException is thrown.
transient Tansient variables will not be serialized. Read or written to and from a stream.
Externalizable java.io.Externalizable interface can be used to implement a more efficient method of serializable methods.
The readObject() will call the readExternal() method to serialize the object.
The writeObject() will call the writeExternal() method to serialize the object.
Client/Server Programming Communications between computers can be created using the java network classes.
java.net.Socket A java.net.Socket object represent one of the TCP/IP based communication link between two programs.
Java handles the detail of the TCP/IP connection.
Socket class A Socket class is the client’s connection. The client can be used to create input and output streams that receive and transmit steams of bytes.
port and host The server has a socket connection to a given port on a given host and opens streams for communication.
Socket( host, port)
Of course an IOException can be thrown.
The stream are connected to a Reader and Writer objects.
Threads are used to create the socket connection because of muli access.
ServerSocket The java.net.ServerSocket are used to create a server connection on the specified port of the server.
ServerSocket( port )
void listen() A ServerSocket uses a listen() method to listen to for a client connection.
Once a connection is established, a Socket object is returned as a client.
Datagram Sockets Another protocol used is the User Datagram Protocol (UDP) used to transmit data packets.
Some packet may be lost, thereby less reliable than TCP/IP.
It simply send and receives packets of byes without worrying about lost data or missing packets.
IO class Exceptions Input and Output stream can generate several exceptions based on the IOException.
EOFException Thrown when an input method hits an unexpected-end of file.
FileNotFoundException Thrown when a file specified in as a String or the File could not be opened.
InterruptedException Thrown when a Thread performing an IO operation is interrupted.
MalformedUrlException Thrown when an when an attempt to create a stream from a URL is unable to interpret the data as a valid address.
ObjectStreamException The abstract class that is the base for all exceptions specific to serializing objects.
boolean createNewFile() Create a new empty file.
File and name filters can be used on the File object.
File Filters FileNameFilter FileFilter
Exam Tip The File object can not change the current directory
To get the current directory use the System static class.String currentDir = System.getProperty(“user.dir”);
Exam Tip To open a file use one of the java.io package with the File object as an argument.