ObjectInputStreamObjectOutputStream工具类
生活随笔
收集整理的這篇文章主要介紹了
ObjectInputStreamObjectOutputStream工具类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
序列化:將數(shù)據(jù)保存到文件;ObjectOutputStream; 反序列化:將文件中的數(shù)據(jù)顯示出來;ObjectInputStream; 在反序列化程序中運(yùn)行后能夠正常輸出Person的相關(guān)信息,但是在目錄下的文件“person.obj”用文本編輯器打開之后卻是亂碼的。這是為什么呢?是不是因為寫出去的編碼和文本編輯器的默認(rèn)編碼采用了不一樣的字符集?然后我們就開始想怎么能夠?qū)⒍叩木幋a格式設(shè)為一致的。 其實(shí),這么想一開始就是錯誤的。為什么這么說呢,因為序列化和反序列化都是基于二進(jìn)制流的,也就是說,在第二步中,其實(shí)就是將person的相關(guān)信息轉(zhuǎn)化為二進(jìn)制存儲在了person.obj這個文件中,那么用文本編輯器打開查看的話當(dāng)然是會出現(xiàn)亂碼的。只有通過反序列化才能將存儲的二進(jìn)制讀取出來,然后正常顯示在控制臺上。 package com.util;import com.bean.*;import java.util.*;
import java.io.*;public class StudentUtil {/*** 從文件中獲取Student集合對象List* */public static List<Student> fileToLst() {List<Student> lsst = null;// 獲取存放學(xué)生集合的文件對象File file = new File("stu.bin");try {if (file.exists()) {// 創(chuàng)建文件輸入流對象FileInputStream fin = new FileInputStream(file);// 創(chuàng)建緩沖區(qū)輸入流對象BufferedInputStream bin = new BufferedInputStream(fin);// 創(chuàng)建對象輸入流ObjectInputStream oin = new ObjectInputStream(bin);// 從對象輸入流中獲取學(xué)生的集合對象lsst = (List<Student>) oin.readObject();oin.close();return lsst;}} catch (FileNotFoundException e) {// TODO Auto-generated catch block
e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block
e.printStackTrace();}return lsst;}/*** 向文件中存放學(xué)生的集合對象* */public static boolean listToFile(ArrayList<Student> lsst) {// 創(chuàng)建文件對象,指定文件存放的路徑File file = new File("stu.bin");// 集合中有元素存在,向文件中寫入數(shù)據(jù)if (lsst != null && !lsst.isEmpty()) {try {FileOutputStream fout = new FileOutputStream(file);// 創(chuàng)建緩沖區(qū)輸出流對象BufferedOutputStream bout = new BufferedOutputStream(fout);// 創(chuàng)建對象輸出流ObjectOutputStream obout = new ObjectOutputStream(bout);obout.writeObject(lsst);obout.flush();obout.close();return true;} catch (FileNotFoundException e) {// TODO Auto-generated catch block
e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();}}return false;}
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/YLQBL/p/6598444.html
總結(jié)
以上是生活随笔為你收集整理的ObjectInputStreamObjectOutputStream工具类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 友盟QQ好友或者空间分享成功,但回调失败
- 下一篇: ASP.NET EntityFramew