2011-12-21 2 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에 그것을받을. 개체가 (패킷)을 사용하여 패킷으로 안내됩니다. 다음과 같이 이것이 어떻게 작동하는지 볼 수 있습니다.

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]은 바이트 배열, 즉 2 진 데이터를 인쇄 할 때 얻을 수 있습니다.

그에서 문자열을 얻으려면, 당신은 인코딩을 알 필요가, 그리고 당신은 할 수있다 : 물론

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

, 데이터가 실제로 인쇄 가능한 데이터가있는 경우에만 작동하는지.

+0

+1 예, 괜찮습니다. 훨씬 좋습니다. 내 통행 금지령을 써야 해. –

1

이것은 정상적인 현상이며 배열 객체를 문자열로 인쇄합니다.

사용 : System.out.println(new String(packet.getMessage());.

즉, 그 안에있는 바이트 중 하나를 빌드하십시오. 그리고 이것은 기본 인코딩을 사용합니다.

2

getMessage()은 바이트 배열을 반환합니다. 배열에 대한 toString() 메서드는 내용을 인쇄하지 않습니다. getMessage()String 대신 반환 할 수 있습니다.