我正在尝试将一堆整数和一个字符串写入字节缓冲区。稍后此字节数组将写入硬盘驱动器。一切似乎都很好,除非我在循环中写字符串时只写入最后一个字符。字符串的解析看起来是正确的,因为我已经检查过了。 它似乎是我使用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());
}
答案 0 :(得分:1)
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)
当然,插入String字节的方式确实无关紧要。我只是建议进行发现实验。