Data Stream 支持primitive 类型I/O,而Object Stream 支持Object类型的I/O.
常用Object Stream classes: ObjectInputstream 和ObjectOutputStream.构造方法:ObjectInputStream(InputStream in),ObjectOutputStream(OutputStream out)
Object Stream classes 都实现ObjectInput 和ObjectOutput接口. 然而这两个接口又继承了data stream 中的DataInput 与DataOutput两个接口,所以,在Object Stream的类中包含了操作primitive 类型的所以方法。
也就是说,也可以用Object Stream类型的类来处理Data stream类型的数据。
代码:
package io.objectstream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.math.BigDecimal; import java.util.Calendar; public class ObjectStreams { static final String dataFile = "D:\\360云盘\\javase\\src\\io\\invoiceobjectdata"; static final BigDecimal[] prices = { new BigDecimal("19.99"), new BigDecimal("9.99"), new BigDecimal("15.99"), new BigDecimal("3.99"), new BigDecimal("4.99") }; static final int[] units = { 12, 8, 13, 29, 50 }; static final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; public static void main(String[] args) throws IOException { ObjectOutput out = null; try { out = new ObjectOutputStream(new FileOutputStream(dataFile)); out.writeObject(Calendar.getInstance()); for (int i = 0; i < prices.length; i++) { out.writeObject(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]); } } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } // ==========================Read data file============================= BigDecimal price = null; BigDecimal total = BigDecimal.ZERO; int unit; String desc; ObjectInput in = null; try { in = new ObjectInputStream(new FileInputStream(dataFile)); Calendar date = null; date = (Calendar) in.readObject(); System.out.format("On %tA, %<tB %<te, %<tY:%n", date); while (true) { price = (BigDecimal) in.readObject(); unit = in.readInt(); desc = in.readUTF(); System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price); total = total.add(price.multiply(new BigDecimal(unit))); } } catch (EOFException e) { System.out.format("For a TOTAL of: $%.4f%n", total); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) in.close(); } } }