java 如何从ByteBuffer读取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30703736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read data from ByteBuffer
提问by sanam_bl
How to read the data stored in ByteBuffer?
如何读取ByteBuffer中存储的数据?
setValue()
- gets value "12 10" and is converted into Hexadecimal value and is stored inString[]
data.write()
- converts data into bytes and stores inByteBuffer
dest
.readBuffer
- How can I read data fromByteBuffer
?
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?
}
回答by Sarit Adhikari
destValue.rewind()
while (destValue.hasRemaining())
System.out.println((char)destValue.get());
}
回答by llogiq
You can get the backing array of a ByteBuffer with .array()
. If you want to convert it to a String, you'll also need to get the current position, or else you will have a lot of zero-bytes at the end. So you'll end up with code like:
您可以使用.array()
. 如果要将其转换为字符串,还需要获取当前位置,否则最后会有很多零字节。所以你最终会得到如下代码:
new String(buf.array(), 0, buf.position())
Edit: Oh, it appears you want the byte values. Those you could either get by calling Arrays.toString(Arrays.copyOf(buf.array(), 0, buf.position())
or loop x
from 0
to buf.position
calling Integer.toString((int)buf.get(x) & 0xFF, 16)
(to get a 2-digit hex code) and collecting the results in a StringBuilder
.
编辑:哦,看来您想要字节值。那些你可以通过调用获取Arrays.toString(Arrays.copyOf(buf.array(), 0, buf.position())
或循环x
从0
到buf.position
调用Integer.toString((int)buf.get(x) & 0xFF, 16)
(以获得2位数的十六进制代码),并收集在一个结果StringBuilder
。