Java I/O

This talk gives a general overviow of Java I/O as used for distributed programming. It is based on: Many of the pictures come from the developerWorks tutorial.

1 Introduction

2 Creating Streams

//Read and write some text
Socket a_socket = new Socket(www.sc.edu, 80);
InputStreamReader isr = new InputStreamReader(a_socket.getInputStream());
BufferedReader in = new BufferedReader (isr);
PrinterWriter out = new PrinterWriter(a_socket.getOutputStream()); 

//Read and write some binary data
Socket socket_data = new Socket(www.sc.edu, 100);
DataInputStream in_data = new DataInputStream(Socket_data.getInputStream());
DataOutputStream out_data = new DataOutputStream(socket_data.getOutputStream());

3 Exceptions

4 Input Stream Classes

5 Output Stream Classes

6 Sources and Sinks

7 Buffering

//Read
BufferedReader input = new BufferedReader (new InputStreamReader(System.in));

//Write
Writer out= newBufferedWriter(new FileWriter("file.out"));

//Write a system-dependent newline. DANGER!!!
out.newLine();

8 Filtering

9 Checksumming

FileOutputputStream os =  new FileOutputStream("Temp1.tmp");

//CDC32 extends Checksum.
CRC32 crc32 = new CRC32();
CheckedOutputStream cos =  new CheckedOutputStream(os, crc32);
cos.write(1);
cos.write(2);

//Get the checksum for this file
long crc = crc32.getValue();

//Write this checksum to the stream.
cos.write(crc);

10 Inflating and Deflating

import java.util.zip.*;
import java.io.*;
class ZipInputStreamExample
{
  public static void main(String argv[])
  {
    try
    {
      FileInputStream fis = new FileInputStream("test.zip");
      ZipInputStream zis = new ZipInputStream(fis);
      ZipEntry ze;
      // Get the first entry
      ze = zis.getNextEntry();
      if (ze == null)
        System.out.println("End entries");
      else
      {
        // Use it as stream or reader
        DataInputStream dis = new DataInputStream(zis);
        int i = dis.readInt();
        System.out.println("File contains " + i);
        zis.closeEntry();
      }
      zis.close();
    }
    catch(Exception e)
    {
      System.out.println(e);
    }
  }
}

11 Data I/O

import java.io.*;
class DataInputOutputExample
{
  
  static BufferedReader system_in = new BufferedReader
    (new InputStreamReader(System.in));
  
  public static void main(String argv[])
  {

    // Create it
    {
      try
      {
        FileOutputStream fos = new FileOutputStream("data.dat");
        DataOutputStream dos = new DataOutputStream(fos);
        // Read in three hotels
        for (int i = 0; i < 3; i++)
        {
          Hotel a_hotel = new Hotel();
          a_hotel.input(system_in);
          a_hotel.write_to_dos(dos);
        }
        dos.close();
      }
      catch(IOException e)
      {
        System.err.println(e);
      }
    }

    // Now read it
    {
      try
      {
        FileInputStream fis = new FileInputStream("data.dat");
        DataInputStream dis = new DataInputStream(fis);
        Hotel a_hotel = new Hotel();
        while (a_hotel.read_from_dis(dis))
        {
          a_hotel.debug_print();
        }
        dis.close();
      }
      catch(IOException e)
      {
        System.err.println(e);
      }
    }

  }
}

class Hotel
{
  private String name;
  private int rooms;
  private String location;
  boolean input(BufferedReader in)
  {
    try 
    {
      System.out.println("Name: ");
      name = in.readLine();
      System.out.println("Rooms: ");
      String temp = in.readLine();
      rooms = to_int(temp);
      System.out.println("Location: ");
      location = in.readLine();
    }
    catch(IOException e)
    {
      System.err.println(e);
      return false;
    }
    return true;
  }
  boolean write_to_dos(DataOutputStream dos)
  {
    try
    {
      dos.writeUTF(name);
      dos.writeInt(rooms);
      dos.writeUTF(location);
    }
    catch(IOException e)
    {
      System.err.println(e);
      return false;
    }
    return true;
  }
  boolean read_from_dis(DataInputStream dis)
  {
    try
    {
      name = dis.readUTF();
      rooms = dis.readInt();
      location = dis.readUTF();
    }
    catch(EOFException e)
    {
      return false;
    }
    catch(IOException e)
    {
      System.err.println(e);
      return false;
    }
    return true;
  }
  void debug_print()
  {
    System.out.println("Name :" + name +
                       ": Rooms : " + rooms + ": at :" + location+ ":");
  }
  static int to_int(String value)
  {
    int i = 0;
    try
    {
      i = Integer.parseInt(value);
    }
    catch(NumberFormatException e)
    {}
    return i;
  }

}        

12 Object Serialization

//To write
FileOutputSream fos = new FileOutputStream("object.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);

//YourClass is serializable
YourClass yc = new YourClass();
oos.writeObject(yc);

//To read.
FileInputStream fis = new FileInputStream ("object.dat");
ObjectInputStream ois = new ObjectInputStream (fis);
YourClass yc;
yc = (YourClass) ois.readObject();


//You can also check the type of the object before casting it.
FileInputStream fis = FileinputStream("object.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object;
object = ois.readObject();
if (object instanceof YourClass)
{
  YourClass yc = object;
  // Perform operations with yc;
}
else if (object instance of AnotherClass)
{
  AnotherClass ac = object;
  // Perform operations with ac
}   

13 Tokenizing

import java.io.*;
import java.util.*;
public class StringTokenizerExample
{
  public static void main(String args[])
  {
    String line = "abc|def?ghi";
    //Sets the delimeters to | and ?
    StringTokenizer st = new StringTokenizer(line, "|?");
    while (st.hasMoreTokens())
    {
      String s = st.nextToken();
      System.out.println("Token is " + s);
    }
  }
}
//Output:
//Token is abc
//Token is def
//Token is ghi

URLs

  1. Java Network Programming, http://www.amazon.com/exec/obidos/ASIN/1565928709/multiagentcom/
  2. Introduction to Java I/O, http://www6.software.ibm.com/developerworks/education/j-javaio/index.html

This talk available at http://jmvidal.cse.sc.edu/talks/javaio/
Copyright © 2009 José M. Vidal . All rights reserved.

28 May 2002, 08:39AM