I'm writing a simple roulette game that can take multiple players at a time.
I'm trying to deserialize a .dat file players.dat
, however I'm getting a FileNotFoundException
that I suspect is due to my main thread running concurrently to another thread.
My main file (note that readObj
is simply a convenience method that uses ObjectInputStream to read the object back):
Collection<Player> mPlayerList = null;
try {
connectToServer();
} catch (IOException e) {
System.err.println("IO exception when trying to write/connect to server");
e.printStackTrace();
}
// read input stream and attempt to deserialize
// stack trace points to the error being from here
try {
mPlayerList = (Collection<Player>) readObj("players.dat");
} catch (IOException e) {
System.err.println("IO exception when trying to read master player list");
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
System.err.println("Class not found exception when trying to read master player list");
e.printStackTrace();
System.exit(1);
}
In my first try
statement, I attempt to connect to a server running off of my computer:
public class GameEngineServerStub {
public static void main(String[] args) throws IOException {
GameEngineImpl myEngine = new GameEngineImpl();
int portNumber = 4444;
boolean listening = true;
// While statement loops forever, waiting for a client to connect.
// Once client connects, accept, create a new Thread, pass the socket to it, and requests it to start
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new GameEngineServerStubThread(serverSocket.accept(), myEngine).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port 4444");
System.exit(-1);
}
}
}
The server launches this thread, which is responsible for requesting a Collection<Player>
object from another file, and attempting to serialize it.
public void run() {
try (
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
Collection<Player> currentPlayers = engine.getAllPlayers();
try {
ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("players.dat"));
objOut.writeObject(currentPlayers);
} catch (IOException e) {
System.err.println("IO Exception when trying to get master player list!");
e.printStackTrace();
System.exit(1);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
I assume that I will need to pause my main
thread, to wait for my serialization thread to finish, but I'm unsure of how to do so.