Question

I want to make server client aplication and use ObjecOutputStream to send Object to client, but in object which I want to send is ObjectOutputStream object and I need to serializable it somehow but I dont know how... any advice?

I need to send object Player:

public class Player implements Serializable{
    ObjectOutputStream out;
    public Player(ObjectOutputStream out){
        this.out = out;
    }
    public send(){
        this.out.writeObject(this);
    }
}

after launch similar code like this an exeption show this:
java.io.NotSerializableException: java.io.ObjectOutputStream

Was it helpful?

Solution

Since ObjectOutputStream doesn't implement Serializable, so your Player class cannot be serialized. To fix it:

class Player implements Serializable {
    private transient ObjectOutputStream out;

    // the rest
}

In my opinion, the Player should not know how to send itself. You can introduce a new class PlayerSender:

class PlayerSender {

    private ObjectOutputStream outputStream;

    public PlayerSender(OutputStream out) {
        this.outputStream = new ObjectOutputStream(out);
    }

    public void send(Player player) {
        this.outputStream.writeObject(player);
    }

}

//---- Usage ----

List<Player> players = // make a bunch of players;

PlayerSender playerSender = new PlayerSender(getNetworkStream());
//PlayerSender playerSender = new PlayerSender(new FileOutputStream("/players/list.txt");
//PlayerSender playerSender = new PlayerSender(socketConnection.getOutputStream());
for (Player player : players) {
    playerSender.send(player);
}

OTHER TIPS

Here is a code that could help

public void toTXT(String fileName)
{
    try
    {
        // Serialize data object to a file
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
        out.writeObject(player); // player is an instance of Player class
        out.close();


    } 
    catch (Exception e) 
    {

    }
}

This is the correct way to write your code:

public class Player implements Serializable{

    public Player(){

    }
    public ObjectOutputStream send(){
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("filename.txt"));
        this.out.writeObject(this);
        return out;
    }
}

And here is your main() function:

public static void main(String args[])
{

    Player player = new Player();
    player.send();

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top