My other sites

Latest News

New Summer Look :)



Streams in Java

Streams and Readers

Streams for Input and Output

InputStream & OutputStream Methods

Basic Stream Classes

Readers and Writers

Reading String Input Example

Decorators - Filters



Writing on an Object Stream

Reading an Object Stream





Streams in Java

- Java hides the operating system from you, so that you can manipulate data as streams in a device/operating system independent way  

Streams and Readers


Streams for Input and Output

- Abstract base classes for input and output functionality

- Defines basic set of methods

- Used to get data from files, other objects, etc

Two base structures:

1. InputStream / OutputStream
Byte streams 8-bit

2. Reader/Writer
Character streams, 16-bit UNICODE, Internationalisation
Efficiency, Buffer (and not byte) operations, Better locking scheme


InputStream & OutputStream Methods

InputStream Methods

OutputStream Methods
int read()

int read(byte[] )

int read(byte[], int, int)

void close

int available()

void write(int)

void write(byte[] )

void write(byte[], int, int)

void close()

void flush()

Basic Stream Classes

- FileInputStream -> ~ path to file

- FileOutputStream

- DataInputStream
- byte readByte(), long readLong(), double readDouble()

- DataOutputStream
- writeByte(byte), writeLong(long), writeDouble(double)

- PipedInputStream

- PipedOutputStream

Readers and Writers

- 16 bit version of Streams for UNICODE

- InputStreamReader(is)

- OutputStreamWriter(os)

- BufferedReader(ir)

- BufferedWriter(iw)

- StringReader(string)

- StringWriter()

Reading String Input Example

import* ;

public class CharInput {

   public static void main(String[] argv) {
      String s;
      InputStreamReader ir;
      BufferedReader in;
      ir = new InputStreamReader(
      in = new BufferedReader(ir); 
      // Can you figure where the try clause needs to go? 
      while ((s = in.readLine()) !=null) {
          System.out.println("Echo line:"+s);

- Platform independent definition of file&directory names

- Has methods to operate and query files and directories

- Constants to represent platform separators
directory ( UNIX has / and DOS \ )
path ( UNIX has : and DOS has ; )

- Creating a new File Object:

File myFile;
myFile = new File("test.dat");
myFile = new File("/", "test.dat");
File myDir = new File("/");
myFile = new File(myDir, "test.dat");

Often Used Methods:

- String getName();
- String getPath();
- String getAbsolutePath();
- String getParent();
- boolean renameTo(File);
- long lastModified();
- long length();
- boolean delete();
- boolean exists();
- boolean canWrite();
- boolean canRead();
- boolean isFile();
- boolean isDirectory();
- boolean mkdir();
- String[] list();

Decorators - Filters

For example, we want an output stream that is both compressed & encrypted

new EncryptedOutputStream(
new GZIPOutputStream(outputStream));

Note: GZIPOutputStream is from


  - Provides a simple lexical analyzer

- Analyzes an input stream or a reader

- Breaks the input up into tokens

- Same concept as StringTokenizer but on a stream

- use int nextToken() to get the next token; this is returned into either sval or nval depending on the type of the token

- determine the type of the token


- eolIsSignificant(), commentChar()



- Ability to save a java object to a stream

- Implementing Serializable enables serialisation

- No methods or fields, just a semantic construct - tag

- NotSerializableException is thrown if the object graph has any non serializable objects - transient modifier

- Can all classes be serialised?
  private void writeObject( out) throws IOException

private void readObject( in) throws IOException, ClassNotFoundException;

Writing on an Object Stream


public class SerializeTest {

   SerializeTest() {
   String st = new String("This is the message!");
   try {
      FileOutputStream f = new FileOutputStream("c:\\test.ser");
      ObjectOutputStream s = new ObjectOutputStream(f);
   catch (IOException e) { 
public static void main(String args[]) { new SerializeTest(); }

Reading an Object Stream

public class UnserializeTest {
   UnserializeTest() {
      String st;
      try {
         FileInputStream f = new FileInputStream("test.ser");
         ObjectInputStream s = new ObjectInputStream(f);
         st = (String) s.readObject();
      catch (Exception e) { 
         System.out.println(e.getMessage()); }
         System.out.println("String:" + st); 

   public static void main(String args[]) { 
      new UnserializeTest(); 



1. Why Integer.parseInt(String) is static ?

2. What would be the output of the following code?

public class TestEquality {
  public static void main(String[] args) {
	    String string1 = new String("Equality");
	    String string2 = new String("Equality");
      if (string1 == string2)
         System.out.println("string1 == string2");
      if (string1.equals(string2)) 
         System.out.println("string1 equals string2");

3. Does it make sense to null terminate ‘\0’ a String in Java?

4. How would you get a random number between 1 and 10?

5. How would you read a String from the console?

6. The Serializable interface provides a way of sending objects to streams; these streams can be later saved as files on the user’s disk. What effect could this have on Java’s security?

7. What happens if you serialize an object, alter the object’s class and try to read it back?


1. Write a small program to simulate the throwing of a six-faced dice, using the java.util.Random Class

2. Use the java.lang.System class to obtain the following system properties.
java.version, java.vendor, java.home
java.class.path,, os.version, user.home, user.dir
Can you find a way to get all the System properties?

3. Use a StreamTokenizer or StringTokenizer in order to parse a simple ASCII Stream from a file named “employee.db”, which contains records of employees. The fields should be:
FirstName, LastName, Department and Salary,
and should be separated by the delimiter “:”.
Every line in the file contains information for one employee only. For every employee, create an employee object (from an appropriate Employee Class), store inside it the info read from the file, and add all the employee objects to a Vector.
Finally, write useful methods to allow a user to gather information about the existing employees, e.g “Who’s the most well-paid employee” and “retrieve all the employees that work in the Accounting Department” etc.