[英]ObjectOutputStream does not write objects when taking BufferedOutputStream
I've done my research but it seems I can't find enough documentation on the subject. 我已经完成了研究,但似乎找不到足够的文档。
When trying out some code on Object streams , I came to notice that putting a BufferedOutputStream inside an ObjectOutputStream causes the file to be ill-written . 当尝试对一些代码对象流 ,我才发现,把一个ObjectOutputStream内的BufferedOutputStream导致生病,写入的文件。 Just to makes things clearer here's the code I've used:
为了使事情更清楚,这是我使用的代码:
public class Objectstream implements Serializable{
private static final long serialVersionUID = 1L;
public int x;
public Objectstream(){}
public Objectstream(int x){
this.x = x;
}
public static void main(String[] args) {
try(
//ObjectOutputStream objOutStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("/homes/f17oudbi/Bureau/o.txt")));//1
ObjectOutputStream objOutStream = new ObjectOutputStream(new FileOutputStream("o.txt"));//2
ObjectInputStream objInputStream = new ObjectInputStream(new FileInputStream("o.txt"));
){
Objectstream obj = new Objectstream(7);
objOutStream.writeObject(obj);
objOutStream.flush();
System.out.println(((Objectstream)objInputStream.readObject()).x);
}catch(EOFException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
} }
If I decomment the first line and comment the second, the written Objectstream just writes \\AC\\ED\\00\\00
in the file (and that's independant of how I change it); 如果我将第一行分解为注释,然后将第二行注释为注释,则编写的Objectstream只会在文件中写入
\\AC\\ED\\00\\00
(这与我对其进行更改的方式无关); But if I keep the code as is, it writes something with the reference on the object and does the job well. 但是,如果我将代码保持原样,它会在对象上写一些带有引用的东西,并且做得很好。
Does anyone have an explanation why is this the case? 有人解释为什么会这样吗?
Edit: 编辑:
I get the following exception java.io.EOFException
pointing to the line where the ObjectOutputStream
method is created. 我得到以下异常
java.io.EOFException
指向创建ObjectOutputStream
方法的行。
You're trying to create the ObjectInputStream
on the same file that you're writing to - you never even get into the body of your try-with-resources block. 您正在尝试在要写入的同一文件上创建
ObjectInputStream
甚至从未进入try-with-resources块的主体。
Here's what happens: 这是发生了什么:
FileOutputStream
: file is empty FileOutputStream
:文件为空 BufferedOutputStream
: file stays empty BufferedOutputStream
:文件保持为空 ObjectOutputStream
: the OOS writes data to the BufferedOutputStream, but it's buffered ObjectOutputStream
:OOS将数据写入BufferedOutputStream,但已缓冲 FileInputStream
FileInputStream
ObjectInputStream
- that tries to read from the input stream, finds it's empty, and throws an exception ObjectInputStream
尝试从输入流中读取,发现它为空,并引发异常 Basically, I'd strongly advise you not to try to read from the same stream you're writing to - I doubt that this is the only problem it will cause. 基本上,我强烈建议您不要尝试从与您正在写入的同一流中读取信息-我怀疑这将是唯一的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.