2019独角兽企业重金招聘Python工程师标准>>>
Java IO 中对象的序列化操作
这是一个在IO中比较基础的问题,但是因为很少用到,很容易遗忘,面试的时候可能会遇到,所以记录到博客上,防止忘记
其实代码很简单:主要是用到两个类ObjectInputStream 和ObjectOutputStream 分别实现对类的读取和写入
注意的一点是:要序列化的类应该实现Serialiable接口,其实是一个空的接口,包含写入和读取的测试程序代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.UUID;
public class TestSerialized {
/**
* 把对象写入文件
* @throws Exception
*/
public static void WriteObject(Object obj)throws Exception{
FileOutputStream fis = new FileOutputStream(new File("c:\\object.obj"));
ObjectOutputStream oos = new ObjectOutputStream(fis);
oos.writeObject(obj);
oos.close();
}
/**
* 从文件读取对象
* @return
* @throws Exception
*/Android的App列表之拖拽ListView(上)
public static Object readObject() throws Exception {
FileInputStream fis = new FileInputStream(new File("c:\\object.obj"));
ObjectInputStream oos = new ObjectInputStream(fis);
return oos.readObject();
}
public static void testWrite() throws Exception{
SerializedClass sc = new SerializedClass();
sc.setId(UUID.randomUUID().toString());
sc.setName("zhougege");
WriteObject(sc);
System.out.println("写入的对象:");
System.out.println(sc.getId());
System.out.println(sc.getName());
}WiiU 理念之魂
public static void testRead() throws Exception{
Object obj = readObject();
SerializedClass sc = (SerializedClass)obj;
System.out.println("读取到的对象:");
System.out.println(sc.getId());
System.out.println(sc.getName());
}
public static void main(String[] args) throws Exception {
testWrite();
testRead();
}
}
写入对象的核心代码
/**
* 把对象写入文件
* @throws Exception
*/
public static void WriteObject(Object obj)throws Exception{
FileOutputStream fis = new FileOutputStream(new File("c:\\object.obj"));
ObjectOutputStream oos = new ObjectOutputStream(fis);
oos.writeObject(obj);
oos.close();
}
读取对象的核心代码
/**
* 从文件读取对象
* @return
* @throws Exception
*/
public static Object readObject() throws Exception {
FileInputStream fis = new FileInputStream(new File("c:\\object.obj"));
ObjectInputStream oos = new ObjectInputStream(fis);
return oos.readObject();
}