cloneinvoices.java

来自「21天学通java的示例程序源代码」· Java 代码 · 共 44 行

JAVA
44
字号
package com.wrox.clone;
import java.io.*;

public class CloneInvoices {
  public static void main(String[] args) {
    try {
      InvoiceItems oInvoiceItems = new InvoiceItems();

      // Add an invoice;
      oInvoiceItems.addInvoice(new InvoiceItem("Widget", 1, 1.00F));

      // Create a Memory I/O Stream to hold the serialized InvoiceItems object;
      ByteArrayOutputStream oByteArrayOutputStream =
        new ByteArrayOutputStream();

      // Serialize the InvoiceItems object and its contents;
      ObjectOutputStream oObjectOutputStream =
        new ObjectOutputStream(oByteArrayOutputStream);
      oObjectOutputStream.writeObject(oInvoiceItems);

      // Save the byte array stream;
      byte[] bSerializedObject = oByteArrayOutputStream.toByteArray();

      // Release the reference to the InvoiceItems object;
      oInvoiceItems = null;

      // Create a Memory I/O Stream to restore the serialized
      // InvoiceItems object;
      ByteArrayInputStream oByteArrayInputStream =
        new ByteArrayInputStream(bSerializedObject);

      // Restore the InvoiceItems object and its contents;
      ObjectInputStream oObjectInputStream =
        new ObjectInputStream(oByteArrayInputStream);
      oInvoiceItems = (InvoiceItems) oObjectInputStream.readObject();

      // Write the details to System.out to confirm the clone was restored;
      InvoiceItem oInvoiceItem = oInvoiceItems.getInvoice();
      oInvoiceItem.printInvoice();
    } catch (IOException e1) {}
    catch (ClassNotFoundException e2) {}
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?