2011-12-21 10 views
0

私の出力は "[B @ b42cbf"でエラーはありません。Javaでは住所の代わりに文字列を印刷するには?

"Server Check"という文字列にする必要があります。

アドレスではなく文字列を出力するようにコードを修正するにはどうすればよいですか?

オブジェクトを印刷するためのコードが複数回変更されましたが、今は次のようになりました。

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

Iパケットを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はい、あなたは大丈夫です。これははるかに優れています。私は私の門に門限を置くべきです。 –

1

これは正常です。配列オブジェクトを文字列として出力しています。

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

つまり、その中のバイトから文字列を構築します。これはデフォルトのエンコーディングを使用することに注意してください。

2

getMessage()はバイト配列を返します。配列のメソッドtoString()は内容を出力しません。 getMessage()Stringを返すことができます。

関連する問題