Java I/O
int
, could be
represented in different ways on different machines. This is a
problem.DataInput
and DataOutput
write
data in a platform-independent form.writeUTF
.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; } }
11 of 13