[英]Java: input stream with byte array
我有一个输入流,每隔几秒钟获取一个字节数组。 我知道字节数组按此顺序始终包含一个long,一个double和一个整数。 是否可以通过输入流(例如DataInputStream)读取此值,或者您能建议我什么?
您可以查看提供方法getLong()
, getDouble()
和getInt()
java.nio.ByteBuffer
。
假设您有一个始终为20字节的任意InputStream
(长8字节,长8字节双精度,4字节Int):
int BUFSIZE = 20;
byte[] tmp = new byte[BUFSIZE];
while (true) {
int r = in.read(tmp);
if (r == -1) break;
}
ByteBuffer buffer = ByteBuffer.wrap(tmp);
long l = buffer.getLong();
double d = buffer.getDouble();
int i = buffer.getInt();
您应该使用以下方法包装ByteBuffer:
ByteBuffer buf=ByteBuffer.wrap(bytes)
long myLong=buf.readLong();
double myDbl=buf.readDouble();
int myInt=buf.readInt();
尽管性能较差,但DataInputStream
会很好:
DataInputStream dis=new DataInputStream(new ByteArrayInputStream(bytes));
long myLong=dis.readLong();
double myDbl=dis.readDouble();
int myInt=dis.readInt();
要从其中任何一个获取字符串,可以重复使用getChar()
。
假设buf
是您的ByteBuffer或DataInputStream,请执行以下操作:
StringBuilder sb=new StringBuilder();
for(int i=0; i<numChars; i++){ //set numChars as needed
sb.append(buf.readChar());
}
String myString=sb.toString();
如果要读取直到缓冲区末尾,请将循环更改为:
readLoop:while(true){
try{
sb.append(buf.readChar());
catch(BufferUnderflowException e){
break readLoop;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.