2014-04-20 58 views
2

我想使服務器客戶端應用程序,並使用ObjecOutputStream發送對象到客戶端,但在我想發送的對象是ObjectOutputStream對象,我需要序列化它以某種方式,但我不知道如何...任何意見?可序列化的ObjecOutputStream對象

我需要發送的對象播放器:

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

發射後類似的代碼,像這樣的exeption顯示此:
java.io.NotSerializableException:java.io.ObjectOutputStream中

回答

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

} 
+0

它不能解決我的問題。在Player類中是不可序列化的ObjectOutputStream對象..我不能發送它 – user3412372

+0

你不應該使用'ObjectOutputStream'作爲屬性。就像我寫的方法一樣使用它。 – padawan