문제

The code reads and writes objects with the help of XStream.

In the block of reading objects from the XML file in, the InputStream object is closed after declaration. That leads to an exception java.io.IOException: Stream Closed on the line

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. 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.

다른 팁

As proposed by Arie the problem is due to

while(in.available() > 0)

the readObject() should be used :

try{  

   List<Player> players = new ArrayList<>();
   while(trye){  
   {
         players.add((Player) objectIn.readObject());
   }  
} catch (EOFException e){};  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top