【问题标题】:Reading fields from bytearray从字节数组中读取字段
【发布时间】:2012-12-03 08:55:19
【问题描述】:

我正在尝试通过 tcp 发送消息。不幸的是,这不起作用,因此我创建了以下代码用于测试目的:

    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”。为什么?我读错了吗?

谢谢!

【问题讨论】:

    标签: tcp inputstream bytebuffer


    【解决方案1】:

    "[B@44f39650" 是对字节数组对象调用toString() 的结果。你在这里做什么:

    String timestamp = tmp.toString();
    

    所以不要那样做。将字节数组转换为 String, 如果您必须这样做,请使用为此目的提供的 String 构造函数。

    但是,您确实应该为此使用 DataOutputStreamDataInputStream 的 API。

    【讨论】:

    • 谢谢,那行得通:) 不太确定 DataInputStream 在这里如何帮助我,因为它也没有提供读取字符串的方法,是吗?
    • @user1809923 它可以为您提供帮助,因为它有 readInt()readUTF()readXXX() 用于相当多类型的 XXX。 readUTF() 返回 String,前提是您使用 writeUTF() 编写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多