问题导入
今天上课的时候写了一段很简单的的输入流输出流程序,然后报错令人十分诧异,让我们来看看代码
Main函数
import java.io.*;
public class Demo02 {
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception{
try{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/Day01/stu.data"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/Day01/stu.data"));
stu s = new stu("李四", 18);
oos.writeObject(s);
stu s_copy=(stu)ois.readObject();
oos.flush();ois.close();
System.out.println(s_copy);
} catch (Exception e) {
e.printStackTrace();
}
}
}
代码分析
很明显这段程序是创建一个对象,然后把对象写入对应存在的路径,然后再把他读出来,用try catch捕捉异常,但是在运行的时候报了如下的错误:
java.io.EOFException
at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2754)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3249)
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:865)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:342)
at Day01.Demo02.main(Demo02.java:10)
这里报了EOF错误,这让我十分纳闷,为什么这样一段简单的程序会报错,这里我查看了stu类
import java.io.Serializable;
public class stu implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String name;
int age;
public stu(String name ,int age ) {
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "stu [name=" + name + ", age=" + age + "]";
}
}
检查完毕没有问题
存对象的data文件
路径问题
一开始改了下路径,路径分为绝对路径和相对路径,这里相对路径要注意从src文件开始
或者像这样,
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("../stu.data"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("../stu.data"));
但是依旧报错
最终根据大佬的建议我把创建流的顺序改了一下,成功运行
成功写入
要先定义oos再定义ois
总结
既然流的顺序如果写错的话就会抛出异常,是不是很多别的流也有这样的顺序要求,接着我又试了试别的流:
FileInputStream fis = new FileInputStream("src/Day01/te.txt");
FileOutputStream fos = new FileOutputStream("src/Day01/te.txt");
FileReader fr = new FileReader("src/Day01/te.txt");
FileWriter fw = new FileWriter("src/Day01/te.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/Day01/stu.data"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/Day01/stu.data"));
DataInputStream dis = new DataInputStream(new FileInputStream("src/Day01/te.data"));
DataOutputStream dos = new DataOutputStream(new FileOutputStream("src/Day01/te.data"));
经验证均无顺序出错,只有object流会出现顺序问题。