0

数秒ごとにバイト配列を取得する入力ストリームがあります。バイト配列には、常に 1 つの long、1 つの double、1 つの整数がこの順序で含まれていることがわかっています。この値を入力ストリーム (DataInputStream など) で読み取ることは可能ですか?

4

2 に答える 2

2

java.nio.ByteBufferメソッドgetLong()getDouble()およびを提供するものを調べることができますgetInt()

InputStream常に 20 バイト (8 バイトの Long、8 バイトの Double、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();
于 2013-07-07T19:08:47.597 に答える
2

次を使用して 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()繰り返し使用できます。

bufByteBuffer または 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;
    }
}
于 2013-07-07T19:09:21.650 に答える