集册 Java实例教程 使用ObjectInputStream和ObjectOutputStream保存和读取各种数据类型

使用ObjectInputStream和ObjectOutputStream保存和读取各种数据类型

欢马劈雪     最近更新时间:2020-01-02 10:19:05

481
使用ObjectInputStream和ObjectOutputStream保存和读取各种数据类型

import java.io.*;

import java.math.BigDecimal;/**来 自 nowjava.com - 时代Java**/

import java.util.Calendar;


public class ObjectStreams {

    static final String dataFile = "invoicedata";


    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,

            ClassNotFoundException {


        ObjectOutputStream out = null;

        try {
        /** 
         来自 时 代 J     a    v  a - nowjava.com**/

            out = new ObjectOutputStream(new BufferedOutputStream(

                    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]);

            }

        } finally {

            out.close();

        }


        ObjectInputStream in = null;

        try {

            in = new ObjectInputStream(new BufferedInputStream(

                    new FileInputStream(dataFile)));


            Calendar date = null;

            BigDecimal price;

            int unit;

            String desc;

            BigDecimal total = new BigDecimal(0);


            date = (Calendar) in.readObject();


            System.out.format("On %tA, %<tB %<te, %<tY:%n", date);


            try {

                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: $%.2f%n", total);

        } finally {

            in.close();

        }

    }

}


展开阅读全文