2012-12-03 62 views
0

我試圖通過tcp發送消息。遺憾的是不工作,所以我創建了下面的代碼用於測試目的:從bytearray讀取字段

public void sendQuestion(String text) { 
     // Set timestamp. 
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
     TimeZone tz = TimeZone.getTimeZone("GMT+01:00"); 
     df.setTimeZone(tz); 
     String date = df.format(new Date()); 

     byte[] dateStr = date.getBytes(); 

     // Set payload. 
     String payloadTemp = date + text; 
     byte[] payload = payloadTemp.getBytes(); 

     // Send the payload. 
     clientOutputThread.send(1, payload); 

      .... 
    } 


public void send(byte type, byte[] payload) { 
      // Calculate and set size of message. 
      ByteBuffer bufferTemp = ByteBuffer.allocate(4); 
      bufferTemp.order(ByteOrder.BIG_ENDIAN); 
      byte[] payloadSize = bufferTemp.putInt(payload.length).array(); 

      byte[] buffer = new byte[5 + payload.length]; 

      System.arraycopy(payloadSize, 0, buffer, 0, 4); 
      System.arraycopy(payload, 0, buffer, 5, payload.length); 

      // Set message type. 
      buffer[4] = type; 

      // TEST: Try reading values again 

      ByteBuffer bb = ByteBuffer.wrap(buffer); 
      // get all the fields: 
      int payload2 = bb.getInt(0); // bytes 0-3 
             // byte 4 is the type 
      byte[] tmp = new byte[19]; // date is 19 bytes 
      bb.position(5); 
      bb.get(tmp); 
      String timestamp = tmp.toString(); 
      byte[] tmp2 = new byte[payload2-19]; 
      bb.get(tmp2); // text 
      String text = tmp2.toString(); 

        .... 
} 

不幸的是,我讀的時間戳和文字是垃圾,那種「[B @ 44f39650」的東西。爲什麼?我讀錯了嗎?

謝謝!

回答

0

「[B @ 44f39650」是在一個字節數組的對象上調用toString()的結果。你在這裏做什麼:

String timestamp = tmp.toString(); 

所以不要那樣做。如果您必須這樣做,則將字節數組轉換爲String,,使用爲此目的提供的字符串構造函數。

但是,您應該真的使用DataOutputStreamDataInputStream的API用於此目的。

+0

謝謝,那工作:)不太確定DataInputStream如何可以幫助我在這裏雖然,因爲它不提供讀取字符串的方法,是嗎? – user1809923

+0

@ user1809923對於很多類型的XXX,它可以幫助你,因爲它有'readInt()','readUTF()','readXXX()'。 'readUTF()'返回一個'String',前提是你用'writeUTF()'寫了它。 – EJP