再写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("文件关闭异常");
}
}
}
}