如何从ByteBuffer

时间:2015-06-08 07:49:55

标签: java bytebuffer

如何读取存储在ByteBuffer中的数据?

  • setValue() - 获取值“12 10”并转换为十六进制值并存储在String[]数据中。
  • write() - 将数据转换为字节并存储在ByteBuffer dest中。
  • readBuffer - 如何从ByteBuffer
  • 读取数据
static String[] data = {};
//value = "12 10";
String setValue(String value) {
    String[] samples = value.split("[ ,\n]+");
    data = new String[samples.length];

    //Generates Hex values
    for (int i = 0; i < samples.length; i++) {
        samples[i] = "0x"+String.format("%02x", Byte.parseByte(samples[i]));
    //data[i] will have values 0x0c, 0x0a
        data[i] = samples[i];
    }
    System.out.println("data :: " +Arrays.toString(samples));
    return value;
}


void write(int sequenceNumber, ByteBuffer dest) {
        for (int i = 0; i < data.length; i++) {
            System.out.println("data[i] in bytes :: "+data[i].getBytes());

            dest.put(data[i].getBytes());           

        }   

    }   

void readBuffer(ByteBuffer destValue)
{
        //How to read the data stored in ByteBuffer?
}

2 个答案:

答案 0 :(得分:2)

destValue.rewind() 
while (destValue.hasRemaining())
     System.out.println((char)destValue.get());
}

答案 1 :(得分:1)

您可以使用.array()获取ByteBuffer的后备数组。如果要将其转换为String,您还需要获取当前位置,否则最后会有很多零字节。所以你最终得到的代码如下:

new String(buf.array(), 0, buf.position())

编辑:哦,看起来你想要字节值。您可以通过调用Arrays.toString(Arrays.copyOf(buf.array(), 0, buf.position())或从x循环0buf.position来调用Integer.toString((int)buf.get(x) & 0xFF, 16)(获取2位十六进制代码)并收集结果为StringBuilder

相关问题