Resources:
Topics:
Input and Output Streams
The abstract classes InputStream and OutputStream contain
the basic I/O interface.
Note: Use the ones from java.io, not Corba.
These have abstract methods to read and write a single byte and implemented
methods to close and handle arrays of bytes.
Look at the Java documentation for these.
There are lots of extensions to each of these.
Here are the tables from the Core Java book.
This does not even count the Reader and Writer classes.
Files and Streams
The simplest ways to get a stream from a file is with FileInputStream and FileOutputStream.
First create a File.
The constructor takes a String parameter, the file name.
File f = new File(filename);
If a file exists, you can find its size with the length method.
Then create a stream:
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f);
Alternatively, you can create these directly from the filename:
FileInputStream fis = new FileInputStream(filename);
FileOutputStream fos = new FileOutputStream(filename);
Note that write will write all you ask, but read may not read all you ask it to.
We will usually use a DataInputStream or a DataOutputStream.
These can easily be made from any input or output stream including
System.in and System.out.
Here are some of the important methods for the DataInputStream:
int read(byte[] b)
int read(byte[] b, int off, int len)
void readFully(byte[] b);
void readFully(byte[] b, int off, int len);
void close()
Here are some of the important methods for the DataOutputStream:
void write(byte[] b, int off, int len)
void flush()
int size()
void close()
General way of figuring out which type of stream to use:
First determine the functionality you need.
Major problem with Java I/O: There is no reliable way to abort a thread that is block waiting for I/O.
Exceptions
Most of the I/O methods and some constructors can throw an exception.
Handle exceptions with try ... catch ... finally.
It is important to close all streams when you are done.
This can be tricky when an error occurs, especially since close can
also throw an error.
Note that the finally clause is executed whether an exception occurs
or not.
Network communication
We will look only at connection-oriented communication.
Server: waits for a connection from a remote client using a given port