我在一个教程网站上阅读了有关 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 = channel.send(buf, new InetSocketAddress("example.com", 80));
他们在创建 ByteBuffer 类对象后添加了 buf.clear() 行。 clear() 用于清除缓冲区。但是最初我们不需要清除对吧??。如果那里需要它,那么我们为什么要使用??。 谢谢。(抱歉,如果有任何语法错误)
最佳答案
也许这只是一个糟糕的教程/网站。如果您刚刚分配了一个全新的ByteBuffer
,则不需要它。你可以使用
ByteBuffer buf = ByteBuffer.wrap(newData.getBytes());
也摆脱 put()
和 flip()
。
关于java - java中ByteBuffer的clear()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42137602/