CharBuffer.put() 不起作用
我尝试使用 CharBuffer.put()
函数将一些字符串放入 CharBuffer
中 但缓冲区留空。
我的代码:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
我尝试在 allocate(1000)
之后与 clear()
或 rewind()
一起使用,但这并没有改变结果。
I try to put some strings to CharBuffer
with CharBuffer.put()
function
but the buffer is left blank.
my code:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
I tried to use with clear()
or rewind()
after allocate(1000)
but that did not change the result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
您缺少的细节是写入将当前指针移动到写入数据的末尾,因此当您打印出来时,它从当前指针开始,而当前指针没有写入任何内容。
Try this:
The detail you're missing is that writing moves the current pointer to the end of the written data, so when you're printing it out, it's starting at the current pointer, which has nothing written.
添加对 < 的调用code>rewind() 就在循环之后。
Add a call to
rewind()
right after the loop.您需要先
flip()
缓冲区,然后才能从缓冲区中读取数据。从缓冲区读取数据之前需要调用flip()
方法。当调用flip()
方法时,limit 被设置为当前位置,position 被设置为0。例如,上面的代码只会打印缓冲区中的字符,而不打印缓冲区中未写入的空间。
You will need to
flip()
the buffer before you can read from the buffer. Theflip()
method needs to be called before reading the data from the buffer. When theflip()
method is called the limit is set to the current position, and the position to 0. e.g.The above will only print the characters in the buffers and not the unwritten space in the buffer.
放入物品后必须倒带,试试这个
You must rewind it after you put in the objects, try this