// File: IO20.java (Module 13) // // Author: Rahul Simha // Created: Nov 28, 1998 // // Writing and reading raw data import java.io.*; // The familiar Person class. class Person { String name; int age; public Person (String name, int age) { this.age = age; // Make sure the length is exactly five. if (name.length() > 5) this.name = name.substring (0,5); else { this.name = name; for (int i=name.length()+1; i<=5; i++) this.name = this.name + " "; } } public String toString () { return "Person: name=" + name + ", age=" + age; } } public class IO20 { public static void main (String[] argv) { try { // Writing using DataInputStream. FileOutputStream fileOut = new FileOutputStream ("Persons.data"); DataOutputStream dos = new DataOutputStream (fileOut); // Create three Person instances. Person p = new Person ("aaa", 16); System.out.println ("Write: " + p); dos.writeChars (p.name); dos.writeInt (p.age); p = new Person ("bbbb", 32); System.out.println ("Write: " + p); dos.writeChars (p.name); dos.writeInt (p.age); p = new Person ("cccccccc", 64); System.out.println ("Write: " + p); dos.writeChars (p.name); dos.writeInt (p.age); dos.close (); // First, let's look at the raw data in the file. FileInputStream fis = new FileInputStream ("Persons.data"); int k = fis.read(); int count = 1; while (k >= 0) { byte b = (byte) k; String hex = Integer.toHexString (b); System.out.println ("Byte #" + count + ": " + hex); count ++; k = fis.read(); } fis.close(); // Now read in the data. fis = new FileInputStream ("Persons.data"); DataInputStream dis = new DataInputStream (fis); char[] nameArray = new char[5]; for (int i=0; i<5; i++) nameArray[i] = dis.readChar(); String name = new String (nameArray); int age = dis.readInt(); System.out.println ("Read: name=" + name + ", age=" + age); nameArray = new char[5]; for (int i=0; i<5; i++) nameArray[i] = dis.readChar(); name = new String (nameArray); age = dis.readInt(); System.out.println ("Read: name=" + name + ", age=" + age); dis.close(); } catch (IOException e) { System.out.println (e); } } }