java可以将序列化以后的对象存入文件中,比如HashMap, 然后还能读出来。对于一些做高速缓存的项目非常有用,比如你从数据库读取了一个分类,希望以后就不要从数据库读取了,从文件读取。那么这种办法非常有用。
如果一个对象没有被序列化,那么无法存入,所以对象必须是序列化的
package com.javaer.examples.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class StoreFileObject {
//java serialize a object to file
public static void writeObject(String path,Object map) throws IOException{
File f=new File(path);
FileOutputStream out=new FileOutputStream(f);
ObjectOutputStream objwrite=new ObjectOutputStream(out);
objwrite.writeObject(map);
objwrite.flush();
objwrite.close();
}
// read the object from the file
public static Object readObject(String path) throws IOException, ClassNotFoundException{
FileInputStream in=new FileInputStream(path);
ObjectInputStream objread=new ObjectInputStream(in);
Object map=objread.readObject();
objread.close();
return map;
}
/**
* @param args
*/
public static void main(String[] args) {
HashMap h = new HashMap();
h.put(‘‘name‘‘, ‘‘walter‘‘);
try {
StoreFileObject.writeObject(‘‘/my.db‘‘, h);
} catch (IOException e) {
e.printStackTrace();
}
}
}
首发于 -
http://java-er.com/blog/java-save-object/
阅读(302) | 评论(0) | 转发(0) |