2011-12-21 65 views
0

我的輸出是「[B @ b42cbf」,沒有錯誤。如何在Java中打印字符串而不是地址?

它應該是一個字符串,表示「服務器檢查」。

如何修復我的代碼以輸出字符串而不是地址?

我打印對象的代碼已被更改多次,但現在如下所示。

System.out.println(packet.getMessage().toString()); 

我的數據包類如下。

import java.io.Serializable; 

public class Packet implements Serializable { 

    final public short MESSAGE = 0; 
    final public short COMMAND = 1; 

    private String _ip; 
    private short _type; 
    private String _source; 
    private String _destination; 
    private byte[] _message; 


    public Packet(String ip, short type, String source, String destination, 
      byte[] message) { 
     this._ip = ip; 
     this._type = type; 
     this._source = source; 
     this._destination = destination; 
     this._message = message; 
    } 

    public String getIP() { 
     return this._ip; 
    } 

    public Short getType() { 
     return this._type; 
    } 

    public String getSource() { 
     return this._source; 
    } 

    public String getDestination() { 
     return this._destination; 
    } 

    public byte[] getMessage() { 
     return this._message; 
    } 
} 

我通過ObjectOutputStream發送數據包,然後將它收到ObjectInputStream中。該對象被封裝在(Packet)包中。你可以看到如何工作如下。

public void sendPacket(Packet packet) throws NoConnection { 
     if (this._isConnected) { 
      try { 
       this._oos.writeObject(packet); 
       this._oos.flush(); // Makes packet send 
      } catch (Exception e) { 
       e.printStackTrace(); 
       this._isConnected = false; 
       throw new NoConnection("No notification of disconnection..."); 
      } 
     } else { 
      throw new NoConnection("No connection..."); 
     } 
    } 

這是監聽者。

@Override 
    public void run() { 
     try { 
      this._ois = new ObjectInputStream(this._socket.getInputStream()); 
      Packet packet = (Packet) this._ois.readObject(); 
      this._listener.addPacket(packet); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

回答

8

[[email protected]是您在打印字節數組(即二進制數據)時得到的結果。

爲了得到一個字符串,你需要知道的編碼,然後你可以這樣做:

String messageStr = new String(packet.getMessage(), "UTF-8"); 

當然,只有當數據實際上是可打印數據的工作。

+0

+1是的,你說得很對,這樣好多了。我應該對我的SO進行宵禁。 – 2011-12-21 08:43:04

1

這是正常的,您正在將數組對象作爲String打印。

用途:System.out.println(new String(packet.getMessage());

也就是說,建立一個字符串中的字符串。並注意這使用默認編碼。

2

getMessage()返回一個字節數組。數組的toString()方法不會打印其內容。您可以改爲getMessage()返回String

相關問題