声明后,InputStream对象关闭

时间:2013-12-29 19:11:23

标签: java inputstream xstream

代码在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)

2 个答案:

答案 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){};