简体   繁体   中英

InputStream object closes after declaration

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM