当我尝试将字符串添加到bytebuffer时,它不会写入文件。虽然我尝试添加int和double,但它工作正常。但对于字符串,它不起作用。
buffer.asCharBuffer().put(value.getValue1());
buffer.asCharBuffer().put(value.getValue2());
答案 0 :(得分:1)
ByteBuffer
并将其大小设置为足够大的数字,以避免缓冲区在向其添加字节时溢出asCharBuffer()
API方法,以便能够将字符直接放入字节缓冲区使用put(String)
API方法,我们可以将String直接放到字节缓冲区
toString()
API方法返回ByteBuffer
内容的字符串表示形式。不要忘记flip()
ByteBuffer
,因为toString()
API方法会显示当前缓冲区位置上的ByteBuffer
内容:
UseByteBufferToStoreStrings
:
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class UseByteBufferToStoreStrings {
public static void main(String[] args) {
// Allocate a new non-direct byte buffer with a 50 byte capacity
// set this to a big value to avoid BufferOverflowException
ByteBuffer buf = ByteBuffer.allocate(50);
// Creates a view of this byte buffer as a char buffer
CharBuffer cbuf = buf.asCharBuffer();
// Write a string to char buffer
cbuf.put("Your sting");
// Flips this buffer. The limit is set to the current position and then
// the position is set to zero. If the mark is defined then it is discarded
cbuf.flip();
String s = cbuf.toString(); // a string
System.out.println(s);
}
}
答案 1 :(得分:0)
如果您想使用String
方法的返回值将getBytes()
添加到ByteBuffer,则可用。
buf.put("Your string".getBytes);