程式目的:檢索一個檔案夾下的檔案是不是存盤了某個類物件的序列化資訊;
遇到的問題:用ObjectInputStream(InputStream is)方法讀取到不含序列化資訊檔案的時候 程式拋出了StreamCorruptedException例外
希望得到的幫助:怎樣判斷一個檔案中是不是存盤了序列化資訊?
StudentSerialization stuseria = new StudentSerialization();
ObjectInputStream ois = null;
try {
File file = new File("D:\\Ideal\\practice\\");
stuseria.searchFile(file); //將file檔案夾下所有的檔案都添加到stuseria.filelist集合中
if (stuseria.filelist.size()!=0){
int num = 0; //查找到的學生物件數量
for (File f:stuseria.filelist){
ois = new ObjectInputStream(new FileInputStream(f));//拋出例外的地方
Object o;
if ((o=ois.readObject()) instanceof Student){
//省略對獲取的物件進行相關處理代碼
}
}
}
//省略相關catch/finally以及關閉流代碼塊
uj5u.com熱心網友回復:
拋出例外的地方加一個try-catch; catch到StreamCorruptedException就continue進入下一次回圈; 問題解決了
修改的代碼如下:
for (File f:stuseria.filelist){
try {
ois = new ObjectInputStream(new FileInputStream(f));//讀取到存盤非序列化檔案時,會拋出StreamCorruptedException例外
}catch (StreamCorruptedException e){
continue;
}
uj5u.com熱心網友回復:
檔案頭里有標識的。Java序列化 - 二進制格式詳解_夫禮者的專欄-CSDN博客_java 二進制序列化
https://blog.csdn.net/lqzkcx3/article/details/79463450
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/246653.html
標籤:Java相關
上一篇:求大佬幫忙我這個idea
