将字符串插入字节缓冲区

Inserting a string into a bytebuffer

我正在尝试将一堆整数和一个字符串写入字节缓冲区。稍后会将此字节数组写入硬盘。一切似乎都很好,除非我在循环中写字符串时只写了最后一个字符。正如我检查过的那样,字符串的解析看起来是正确的。 这似乎是我使用 bbuf.put 语句的方式。之后我需要刷新它吗?为什么 .putInt 语句工作正常而不是 .put

//write the PCB from memory to file system
private static void _tfs_write_pcb()
{

    int c;
    byte[] bytes = new byte[11];


    //to get the bytes from volume name
    try {
        bytes = constants.filename.getBytes("UTF-8");           //convert to bytes format to pass to function
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }       

    ByteBuffer bbuf = ByteBuffer.allocate(bl_size);

    bbuf = bbuf.putInt(rt_dir_start);
    bbuf = bbuf.putInt(first_free_data_bl);
    bbuf = bbuf.putInt(num_bl_fat);
    bbuf = bbuf.putInt(bl_size);
    bbuf = bbuf.putInt(max_rt_entries);
    bbuf = bbuf.putInt(ft_copies);


    for (c=0; c < vl_name.length(); c++) {
        System.out.println((char)bytes[c]);
        bbuf = bbuf.put(bytes[c]);
    }

    _tfs_write_block(1, bbuf.array());

}

ByteBuffer 有一个放置字节数组的方法。有理由一次放一个吗?我注意到 put(byte) 也是抽象的。

所以 for 循环被简化为:

bbuf = bbuf.put(bytes, 6, bytes.length);

http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte:A-

编辑: Javadoc 指定 put(byte[]) 从索引 0 开始,因此请改用 put(byte[], index, length) 形式。

public final ByteBuffer put(byte[] src)

Relative bulk put method  (optional operation).

This method transfers the entire content of the given source byte array
into this buffer. An invocation of this method of the form dst.put(a) 
behaves in exactly the same way as the invocation

     dst.put(a, 0, a.length) 

当然,如何插入字符串字节并不重要。我只是建议进行发现实验。