代码在XStream
的帮助下读取和写入对象。
在从XML文件in
读取对象的块中,InputStream
对象在声明后关闭。这会在行
java.io.IOException: Stream Closed
ObjectInputStream objectIn = stream.createObjectInputStream(in)
编译时。
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()));
}
}
}
}
堆栈跟踪是:
Exception in thread "main" java.io.IOException: Stream Closed at java.io.FileInputStream.available(Native Method) at capitel02.PlayersXStreamIO.main(PlayersXStreamIO.java:39)
答案 0 :(得分:0)
我想在包装FileInputStream
以创建ObjectInputStream
时,实现已经解析完整文件并关闭它。因此,您将获得流末尾异常。解决方案是不访问文件输入流本身,而只访问ObjectInputStream
变量引用的已创建objectIn
。
答案 1 :(得分:0)
正如Arie所提出的,问题是由于
while(in.available()&gt; 0)
应该使用readObject():
try{
List<Player> players = new ArrayList<>();
while(trye){
{
players.add((Player) objectIn.readObject());
}
} catch (EOFException e){};