[英]InputStream object closes after declaration
The code reads and writes objects with the help of XStream
. 该代码在
XStream
的帮助下读写对象。
In the block of reading objects from the XML file in
, the InputStream
object is closed after declaration. 在从中的XML文件读取对象的块
in
,在声明后关闭InputStream
对象。 That leads to an exception java.io.IOException: Stream Closed
on the line 这导致异常
java.io.IOException: Stream Closed
ObjectInputStream objectIn = stream.createObjectInputStream(in)
when compiling. 编译时。
import java.io.*;
import java.util.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class PlayersXStreamIO
{
public static void main(String... args) throws IOException, ClassNotFoundException
{
XStream stream = new XStream(new DomDriver());
stream.setMode(XStream.ID_REFERENCES);
if(args.length == 1)
{
try(OutputStream out = new FileOutputStream(args[0]);
ObjectOutputStream objectOut = stream.createObjectOutputStream(out))
{
Player max = new Player("max");
max.setScore(5);
Player moritz = new Player("moritz");
moritz.setScore(3);
objectOut.writeObject(max);
objectOut.writeObject(moritz);
}
}
else
{
try(InputStream in = new FileInputStream(args[0]);
ObjectInputStream objectIn = stream.createObjectInputStream(in))
{ // in.closed = true;
List<Player> players = new ArrayList<>();
while(in.available() > 0)
{
players.add((Player) objectIn.readObject());
}
System.out.println(Arrays.toString(players.toArray()));
}
}
}
}
The stack trace is: 堆栈跟踪为:
Exception in thread "main" java.io.IOException: Stream Closed at java.io.FileInputStream.available(Native Method) at capitel02.PlayersXStreamIO.main(PlayersXStreamIO.java:39)
I guess that while wrapping the FileInputStream
for the creation of an ObjectInputStream
, the implementation already parses the complete file and closes it. 我猜想在包装
FileInputStream
来创建ObjectInputStream
,实现已经解析了完整的文件并关闭了它。 Therefore, you get an end-of-stream exception. 因此,您将收到一个流结束异常。 The solution would be to not access the file input stream itself, but only the created
ObjectInputStream
as referenced by the objectIn
variable. 解决方案是不访问文件输入流本身,而仅访问由
objectIn
变量引用的创建的ObjectInputStream
。
As proposed by Arie the problem is due to 正如Arie所提出的,该问题是由于
while(in.available() > 0)
while(in.available()> 0)
the readObject() should be used : 应该使用readObject():
try{
List<Player> players = new ArrayList<>();
while(trye){
{
players.add((Player) objectIn.readObject());
}
} catch (EOFException e){};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.