Java中物件流使用的一個注意事項
阿新 • • 發佈:2018-12-29
再寫jsp的實驗作業的時候,需要用到java中物件流,但是碰到了之前沒有遇到過的情況,改bug改到崩潰!!記錄下來供大家分享
如果要用物件流去讀取一個檔案,一定要先判斷這個檔案的內容是否為空,如果為空的話,就是連物件流的例項物件也不要建立,一建立就會報錯。
錯誤程式碼例項:
public static void main(String[] args){
ObjectInputStream ois = null;
File file = new File("F:\\MessageBroad.txt");
try{
ois = new ObjectInputStream(new FileInputStream(file));//一建立例項就會報錯
Student stu = (Student) ois.readObject();
System.out.println(stu);
} catch(IOException exception){
exception.printStackTrace();
} catch(ClassNotFoundException e){
e.printStackTrace();
} finally{
try{
ois.close();
}catch(IOException e){
System.out.println("檔案關閉異常");
}
}
}
具體錯誤如下:
所以在讀取之前,一定要判斷這個檔案是否存在且內容是否為空:
更改程式碼如下:
public static void main(String[] args){
ObjectInputStream ois = null;
File file = new File("F:\\MessageBroad.txt");
if(!file.exists() || file.length()!=0) {//特別判斷一下
try{
ois = new ObjectInputStream(new FileInputStream(file));
Student stu = (Student) ois.readObject();
System.out.println(stu);
} catch(IOException exception){
exception.printStackTrace();
} catch(ClassNotFoundException e){
e.printStackTrace();
}finally{
try{
ois.close();
}catch(IOException e){
System.out.println("檔案關閉異常");
}
}
}
}