2013-07-07 36 views
0

我有一个输入流,每隔几秒就获取一个字节数组。我知道字节数组总是按顺序包含一个long,一个double和一个整数。是否有可能通过输入流(例如DataInputStream)读取此值,或者您可以告诉我什么?Java:输入流与字节数组

+0

可以使用'DataInputStream',就像你说的。你有什么理由不去? – Joni

+0

不,我不知道如何将bytearrayinputstream与正常输入流组合起来 – Maxii

回答

2

你应该考虑使用包裹字节缓冲区:

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; 
    } 
} 
+0

谢谢。当字节数组包含一个字符串。是否也可以用datainputstream读取它? – Maxii

+0

@Maxii是的,通过重复readChar()和StringBuilder的方式。如果您希望我可以将其添加到答案中。 – hexafraction

+0

这将是不错的 – Maxii

2

你可以看看java.nio.ByteBuffer,它提供了getLong(),getDouble()getInt()的方法。

假设你总是20个字节(8字节长,8字节双,4字节智力)得到了一个任意InputStream

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();