My other sites

Latest News

New Summer Look :)










Package java.io

 

Streams in Java

Streams and Readers

Streams for Input and Output

InputStream & OutputStream Methods

Basic Stream Classes

Readers and Writers

Reading String Input Example

java.io.File

Decorators - Filters

StreamTokenizer

Serializable

Writing on an Object Stream

Reading an Object Stream

Quiz

Exercises

 

 


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()

skip(long)
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 java.io.* ;

public class CharInput {

   public static void main(String[] argv) {
      String s;
      InputStreamReader ir;
      BufferedReader in;
      ir = new InputStreamReader(System.in)
      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);
      }
   } 
}


java.io.File


- 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 java.util.zip


StreamTokenizer

  - 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

- TT_EOF, TT_EOL, TT_NUMBER, TT_WORD

- eolIsSignificant(), commentChar()

 

Serializable

- 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(java.io.ObjectOutputStream out) throws IOException

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;


Writing on an Object Stream

 
import java.io.*;

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);
      s.writeObject(st);
      s.close();
   }
   catch (IOException e) { 
      System.out.println(e.getMessage()); 
   }
}
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();
         s.close();
      }
      catch (Exception e) { 
         System.out.println(e.getMessage()); }
         System.out.println("String:" + st); 
      }

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

 

Quiz


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?

Exercises


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.name, os.version
user.name, 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.