java.io.StreamCorruptedException: invalid type code:
这个异常时在io输入输出流的练习中遇到的,为了使写进到文件中的内容不会被覆盖,
代码为ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(path,true)));在读取文件时就会遇到这个错误,网上的解答是“一个线程里面同时new了多个ObjectOutputStream流。这在ObjectOutputStream是不允许的,其它的流可以。ObjectOutputStream有锁机制”现在还没有弄明白这个问题。。。
老师给出的解答,是因为往文件里写的时候每写一次就会写一个头文件,这样读的时候读到第二个头文件就会报错,正确的做法是重写ObjectOutputStream方法
public class ObjectSave {
/**
* @param args
* @throws IOException
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) {
ObjectOutputStream out = null;
ObjectInputStream in = null;
List<User> list = new ArrayList<User>();
list.add(new User("admin", "admin", "123", 1));
list.add(new User("zhang", "zhang", "123", 0));
String path = "d://abc";
try {
//判断文件大小并调用不同的方法
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file, true);
if(file.length()<1){
out = new ObjectOutputStream(fos);
}else{
out = new MyObjectOutputStream(fos);
}
//out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path,true)));
//out.writeObject(Calendar.getInstance());
//判断文件大小并调用不同的方法
for (int i = 0; i < list.size(); i++) {
out.writeObject(list.get(i));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
in = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(path)));
//Calendar date = (Calendar) in.readObject();
//System.out.format("On %tA, %<tB %<te, %<tY:%n", date);
while (true) {
User user = (User) in.readObject();
System.out.println(user.getName());
}
} catch (EOFException e) {
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream() throws IOException {
super();
}
public MyObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
return;
}
}