我正在尝试将一堆整数和一个字符串写入字节缓冲区。稍后这个字节数组将被写入硬盘。一切似乎都很好,除了当我在循环中写入字符串时只写入最后一个字符。正如我所检查的那样,字符串的解析看起来是正确的。 这似乎是我使用 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)
当然,如何插入字符串字节并不重要。我只是建议进行发现实验。
关于java - 将字符串插入字节缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922834/