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羣相互學習哦~~