Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture
Background • Java’s I/O model is defined in terms of streams—ordered sequences of data with a source or destination. • Initially, these were (8-bit) byte streams like cin, cout, and cerr for C++. The corresponding byte streams for Java are: • System.in (an InputStream) • System.out (a PrintStream) • System.err (an unbuffered PrintStream) • Later, Unicode character streams were added. These are called Readers and Writers. • These classes and interfaces are found in java.io.* • This is only a short introduction to a long subject! Read the text! Test questions on this material!
Stacking Streams • The important concept in working with Java I/O is stacking streams. • That is, you apply adaptors to a stream to specialise it for a specific task. • For example, a File can be used via a FileStream. • A .gz file can be used via a GZIPInputStream.
Some Byte Stream Operations • java.io.InputStream (base class for byte input) • int read()—reads a byte • int read(byte)—reads an array of bytes • void close()—closes the stream • java.io.OutputStream (base class for byte output) • void write(int)—writes a byte passed as int • void write(byte)—writes an array • void flush()—flushes the stream • void close()—closes the stream
Some Character Stream Operations • java.io.Reader • int read()—reads a Unicode character • int read(char)—reads a character array • boolean ready()—returns true if there is data to read • void close() • java.io.Writer • void write(int)—writes a character • void write(char) • void write(String)—writes a String • void flush() • void close()
Formatted Input/Output • DataInput and DataOutput are interfaces used to transfer data other than bytes or characters (e.g., binary data). Implemented by: • DataInputStream—readType() • DataOutputStream—writeType() • RandomAccessFile—implements both and allows positioning in the file. where Type includes all the primitive types. readLine(), writeBytes(String), writeChars(String), and writeUTF(String) are used for String data.
Data Conversion • The wrapper classes for the primitive types (e.g, Double for double) provide static methods for data conversion from a String to that type. • All classes also define a toString() method to convert the class data to a String. This is used in println() and when Strings are constructed using the + and += operators. If you want this method to be useful, you should override the default method inherited from Object. • Test questions!
Various InputStreams • FileInputStream—built around a file. • PipedInputStream—PipedInputStreams are connected to PipedOutputStreams and are used between threads. • ByteArrayInputStream—Has an internal byte array provided by the creator of the stream and where the data are stored. • StringBufferInputStream—Like a ByteArrayInputStream. The internal buffer is a String. • SequenceInputStream—Reads from multiple streams, finishing one before going on to the next.
More InputStreams • FilterInputStream—Generally built around some other InputStream, using it as a source of data and doing further conversions. This ‘stacking’ can involve multiple filters. Examples include: • BufferedInputStream—Buffers the input and supports mark and reset operations. • DataInputStream—Formatted input operations. • LineNumberInputStream—Reads one line at a time, keeping count • PushBackInputStream—Allows the last byte to be ‘unread’ if desired. Useful for user interfaces.
Various OutputStreams • PrintStream—provides print(arg) and println(arg) operations to output data in a readable form. Both operate by applying the toString() method to arg and then printing the resulting String. println() outputs an end of line as well. • File-, Piped-, ByteArray-, Filter-, Buffered-, and DataOutputStream work generally as you would be expect.
Unicode Character Streams • BufferedReader, BufferedWriter, LineNumberReader • CharArrayReader, CharArrayWriter • FilterReader, PushBackReader, FilterWriter • InputStreamReader, OutputStreamWriter, FileReader, FileWriter • PipedReader, PipedWriter • StringReader, StringWriter • PrintWriter
Files and Directories • An instance of class File represents the pathname (a String) to some file or directory. • File creation and deletion are handled through the File class. • There are some problems having to do with pathnames for files in Java. No bugs; just a collection of surprises.
File Input/Output • A FileInputStream or FileOutputStream is built around a pathname or a File. • Otherwise, it is basically a Stream of the appropriate type. • You can build a FilterInputStream or a FilterOutputStream around these streams.
Data Compression • Specialized filter streams exist to operate on data. • E.g., java.util.zip.GZIPOutputStream if created around another OutputStream will apply gzip compression to the data. • You can also use other classes in the java.util package to generate a checksum for the stream. • The class java.util.zip.ZipFile allows you to access a ZIP archive and read the entries through a stream.
Interfacing to Arrays • The ByteArrayXXX, StringReader/ StringWriter and CharArrayXXX streams allow you to read and write data stored in byte arrays and character strings.
Serialization • This is the capacity to serialize objects, sending them over a stream and deserializing them at the other end to reconstruct the object. This can also be used to save objects offline. • java.io.ObjectOutputStream and java.io.ObjectInputStream participate in this. • Methods used: writeObject() and readObject(). • Used in: • Remote Method Invocation (RMI) • Handling persistent objects • Distributed agent networks
Networking • In the java.net.* package. • Supports TCP and UDP protocols. • URL class is used to represent a Uniform Resource Locator • Also supports sockets/ports with the Socket class. I have watched one of my students write a working IRC client in Java in less than 15 minutes. • Secure Socket Layer is available in Java 1.4.
Logging • New in Java 1.4 • In the java.util.logging.* package. • Automates the creation of a log with multiple severity thresholds. • Can be used to create an audit trail for security.
Non-Blocking I/O • New for Java 1.4 • In java.nio.* • Traditionally, Java I/O was blocking, with the thread having to wait for its data. This is non-blocking I/O. • Supports high-performance I/O.
XML • New for Java 1.4 • Supports XML documents and document formats. • SAXP, JAXP, and XDOC. • Used in JavaServer Pages. • If you care about XML, you care a lot.