Source of ObjectRandomAccessFile.java


  1: import java.io.*; 
  2: 
  3: public class ObjectRandomAccessFile extends RandomAccessFile {
  4: 
  5:   /*
  6:      File format:
  7:      header: 32 bytes 
  8:      block: 
  9:             int count    4 bytes 
 10:             object       count bytes
 11: 
 12: 
 13:    */
 14: 
 15:   protected ByteArrayOutputStream bout; 
 16:   protected byte[] buf; 
 17: 
 18:   public ObjectRandomAccessFile(String name, String mode) throws IOException {
 19:     super(name, mode); 
 20:     bout = new ByteArrayOutputStream(); 
 21:   }
 22:   
 23:   public ObjectRandomAccessFile(File file, String mode) throws IOException {
 24:     super(file, mode); 
 25:     bout = new ByteArrayOutputStream(); 
 26:   }
 27: 
 28:   public int writeObject(Object obj) throws IOException {
 29:     if (obj != null &&
 30:         obj instanceof Serializable) {
 31:       ObjectOutputStream objout = new ObjectOutputStream(bout); 
 32:       objout.writeObject(obj); 
 33:       int count = bout.size(); 
 34:       byte[] buf = bout.toByteArray(); 
 35:       writeInt(count); 
 36:       write(buf, 0, count);         
 37:       bout.reset(); 
 38:       return count + 4; 
 39:     } else {
 40:       return 0; 
 41:     }
 42:   }
 43: 
 44:   public Object readObject() throws IOException, ClassNotFoundException {
 45:     int count = readInt();
 46:     if (buf == null ||
 47:         count > buf.length) {
 48:       buf = new byte[count]; 
 49:     }
 50:     read(buf, 0, count); 
 51:     ObjectInputStream objin = 
 52:         new ObjectInputStream(new ByteArrayInputStream(buf, 0, count)); 
 53:     Object obj = objin.readObject(); 
 54:     objin.close(); 
 55:     return obj; 
 56:   }
 57: 
 58:   public static void main(String[] args) {
 59:     if (args.length > 0) {
 60:       try {
 61:         ObjectRandomAccessFile out = new ObjectRandomAccessFile(args[0], "rw"); 
 62:         Object[] obj = { "Tic", "Tac", "Toe" }; 
 63:         long offset = 0; 
 64:         int count; 
 65:         for (int i = 0; i < obj.length; i++) {
 66:           count = out.writeObject(obj[i]); 
 67:           System.out.println(obj[i] + " written at offset " + offset + 
 68:                              " size = " + count);
 69:           offset += count; 
 70:         }
 71:       } catch (IOException e) {}
 72:     }
 73:   }
 74: 
 75: } 
 76: 
 77: