Serializable ObjecOutputStream对象

时间:2014-04-20 18:49:21

标签: java serializable objectoutputstream

我想制作服务器客户端应用程序并使用ObjecOutputStream将Object发送到客户端,但是我要发送的对象是ObjectOutputStream对象,我需要以某种方式将其序列化,但我不知道如何...任何建议?

我需要发送对象播放器:

public class Player implements Serializable{
    ObjectOutputStream out;
    public Player(ObjectOutputStream out){
        this.out = out;
    }
    public send(){
        this.out.writeObject(this);
    }
}
启动后类似的代码如此例外显示了这一点:
java.io.NotSerializableException:java.io.ObjectOutputStream

2 个答案:

答案 0 :(得分:2)

由于ObjectOutputStream没有实现Serializable,因此您的Player类无法序列化。解决它:

class Player implements Serializable {
    private transient ObjectOutputStream out;

    // the rest
}

在我看来,Player不应该知道如何发送自己。您可以引入新课程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);
}

答案 1 :(得分:0)

这是一个可以提供帮助的代码

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

    }
}

这是编写代码的正确方法:

public class Player implements Serializable{

    public Player(){

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

这是你的main()功能:

public static void main(String args[])
{

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

}