java中ByteBuffer的clear()方法
我在一个教程网站上读到了关于DatagramChannel的内容java中ByteBuffer的clear()方法,java,Java,我在一个教程网站上读到了关于DatagramChannel的内容 String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); int bytesSent = cha
String newData = "New String to write to file..."
+ System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("example.com", 80));
他们在创建ByteBuffer类对象之后添加了行buf.clear()。clear()用于清除缓冲区。但最初我们不需要清除右侧???。如果需要,那么为什么要使用??。
谢谢。(对不起,如果有语法错误的话)也许这只是一个糟糕的教程/网站。如果您刚刚分配了一个全新的
ByteBuffer
,则不需要它。你可以用
ByteBuffer buf = ByteBuffer.wrap(newData.getBytes());
为了摆脱
put()
和flip()
。也许这只是一个糟糕的教程/网站。如果您刚刚分配了一个全新的ByteBuffer
,则不需要它。你可以用
ByteBuffer buf = ByteBuffer.wrap(newData.getBytes());
要摆脱put()
和flip()
。flip()用于更改模式(从/到)写入(到/从)读取模式。默认模式是什么??如果是写入模式,则buf.flip()在channel.send之前是错误的(buf,new InetSocketAddress(“example.com”,80));行或它是没有意义的,只写对了??没有“读模式”或“写模式”。Flip只会翻转缓冲区,将位置设置为0并限制为旧位置,就像javadoc解释的那样。Flip()用于更改模式(从/到)写入(从/到)读取模式。默认模式是什么??如果是写入模式,则buf.flip()在channel.send之前是错误的(buf,new InetSocketAddress(“example.com”,80));行或它是没有意义的,只写对了??没有“读模式”或“写模式”。Flip只是翻转缓冲区,将位置设置为0并限制为旧位置,就像javadoc解释的那样。