ObjectInputStream能够让你从输入流中读取Java对象,而不需要每次读取一个字节。你可以把InputStream包装到ObjectInputStream中,然后就可以从中读取对象了
ObjectOutputStream能够让你把对象写入到输出流中,而不需要每次写入一个字节。你可以把OutputStream包装到ObjectOutputStream中,然后就可以把对象写入到该输出流中了
ObjectInputStream和ObjectOutputStream还有许多read和write方法,比如readInt、writeLong等等,详细信息请查看 http://docs.oracle.com/javase/7/docs/api/
这里操作的bean 必须要序列化 至于序列化是啥就自己去百度吧 implements Serializable
首先说 ObjectOutputStream 把对象转成文件
public static void objectToFile(Object obj, String outputFile) {
ObjectOutputStream oos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(outputFile));
oos = new ObjectOutputStream(fos);
//开始写入
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
ObjectInputStream就读出bean了 直接用bean接收就行了
public static Object fileToObject(String fileName) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
return null;
}
很简单的几个方法调用
使用:
实体:
public class A implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8425494920969357915L;
public String n = "哈哈";
public String getN() {
return n;
}
public void setN(String n) {
this.n = n;
}
public A(String n) {
super();
this.n = n;
}
public A() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "A [n=" + n + "]";
}
}
感觉这个在项目中还是有用的,有疑问可以加上面的qq群相互学习哦~~