0

この奇妙な問題に遭遇したとき、私は ByteBuffers と IntBuffers を扱っていました。ここにコードがあります -

public static void main(String[] args) {
    File file = null;
    FileOutputStream fos = null;
    FileChannel fc = null;
    ByteBuffer bb = ByteBuffer.allocate(1024);
    IntBuffer ib = bb.asIntBuffer();

    ib.put(458215);
    // System.out.println(bb.getInt());  //uncomment this for the program to work flawlessly

    try {
        // Initialize with object references
        file = new File("E:/demjavafiles/text.txt");
        fos = new FileOutputStream(file);
        fc = fos.getChannel();
        System.out.println("Object refrence variables file, fos, fc initialized. Now writing to file....");
        System.out.println("before flip positon : " + bb.position()+ "\n limit: " + bb.limit());
        bb.flip();
        System.out.println("after flip positon : " + bb.position()+ "\n limit: " + bb.limit());

        fc.write(bb);// write buffer
        fc.close();
        System.out.println("buffer written successfully!!");

    } catch (Exception e) {
        System.outprintln("oh oh an error occured D: heres some message 'bout it.");
        e.getMessage();
        e.printStackTrace(System.out);
    } finally {

        System.out.println("End of program....");

    }

}

ご覧のとおり、プログラムは と を作成しByteBuffer、クラスのメソッドをIntBuffer使用してを 4 バイトとしてに追加します。try ブロックステートメントがコメントされる前にプログラムを実行したとき、 これが私の出力でした-put()IntBufferintByteBufferSystem.out.println(bb.getInt());

Object reference variables file, fos, fc initialized. Now writing to file....
before flip position : 0
limit: 1024
after flip posiiton : 0
limit: 0
buffer written successfully!!
End of program....

ステートメントのコメントを外して再度実行すると、 System.out.println(bb.getInt()); これが私の出力でした-

458215
Object reference variables file, fos, fc initialized. Now writing to file....
before flip position : 4
limit: 1024
after flip position : 0
limit: 4
buffer written successfully!!
End of program....

では、なぜこれが起こっているのか誰か教えてください。

4

3 に答える 3

1

JavaDoc から

public final Buffer Flip()

このバッファを反転します。リミットは現在の位置に設定され、次に位置がゼロに設定されます。マークが定義されている場合、それは破棄されます。

バッファーから何かを読み取る前に、position == 0、limit ==0 です。したがって、反転後、位置 == 0、制限 == 0 になります。

するとgetInt()、position は 4 ずつ増加します。つまり、position == 4, limit == 0 です。次にflip()、JavaDoc の言うことを実行します: position == 0, limit == 4.

于 2014-05-07T09:49:46.907 に答える