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.