集册 Java实例教程 反序列化对象

反序列化对象

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

470
反序列化对象

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.FileInputStream;/* 来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInputStream;


public class Main {

  public void m() {

    try {

      // Deserialize from a file

      File file = new File("filename.ser");

      ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));

      // Deserialize the object

      javax.swing.JButton button = (javax.swing.JButton) in.readObject();

      in.close();


      // Get some byte array data

      byte[] bytes = getBytesFromFile(file);


      // Deserialize from a byte array

      in = new ObjectInputStream(new ByteArrayInputStream(bytes));
      /**
       * n o w j a v a . c o m 提 供 
      **/

      button = (javax.swing.JButton) in.readObject();

      in.close();

    } catch (ClassNotFoundException e) {

    } catch (IOException e) {

    }

  }


  // Returns the contents of the file in a byte array.

  public static byte[] getBytesFromFile(File file) throws IOException {

    InputStream is = new FileInputStream(file);


    // Get the size of the file

    long length = file.length();


    if (length > Integer.MAX_VALUE) {

      // File is too large

    }


    // Create the byte array to hold the data

    byte[] bytes = new byte[(int) length];


    // Read in the bytes

    int offset = 0;

    int numRead = 0;

    while (offset < bytes.length

      
展开阅读全文