java把对象数组存入文件中再还原来

这种情况必须用到对象的序列化。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
 
/**
 * 你这种情况必须用到对象的序列化
 * @author QUAN
 *
 */
public class Test
{
    /**
     * 保存对象
     * @param obj
     * @throws IOException
     */
    public static void saveObject(Object obj) throws IOException
    {
        File file = new File("D:/test/file.ser");
        if (!file.exists())
        {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(obj);
        oos.close();
    }
 
    /**
     * 读取对象
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object readObject() throws IOException,
            ClassNotFoundException
    {
        InputStream is = new FileInputStream("D:/test/file.ser");
        ObjectInputStream ois = new ObjectInputStream(is);
        Object obj = ois.readObject();
        ois.close();
        return obj;
    }
 
    public static void main(String[] args)
    {
        Plane p = new Plane();
        p.setId(1);
        p.setName("MH370");
 
        Plane p1 = new Plane();
        p1.setId(2);
        p1.setName("Air Plane One");
 
        Plane[] fly = { p, p1 };
         
        try
        {
            saveObject(fly);
             
            Plane[] result = (Plane[])readObject();
             
            for(Plane e : result)
            {
                System.out.println("id:" + e.getId() + "\t" + "name:" + e.getName());
            }
             
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
 
    }
}
 
class Plane implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 6865564924659901756L;
 
    private int id;
 
    private String name;
 
    public int getId()
    {
        return id;
    }
 
    public void setId(int id)
    {
        this.id = id;
    }
 
    public String getName()
    {
        return name;
    }
 
    public void setName(String name)
    {
        this.name = name;
    }
 
}

  转自:java把对象数组存入文件中再还原来_百度知道 (baidu.com)

posted @ 2022-04-11 21:22  信铁寒胜  阅读(136)  评论(0编辑  收藏  举报