Java NIO.为什么flip()方法会破坏我的程序?

use*_*011 0 java nio bytebuffer socketchannel

下面的Java代码:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Test {
    public static void main(String args[]) throws IOException {

        SocketChannel c = SocketChannel.open();
        c.connect(new InetSocketAddress("google.com", 80));

        ByteBuffer b = ByteBuffer.allocate(1024);
        b.put("Request".getBytes());

        System.out.println("Write: " + c.write(b));

        int i;
        while ((i = c.read(b)) != -1) {

            System.out.println("Read: " + i);
            b.clear();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实际结果:

写:1017阅读:0阅读:1024阅读:44

第一次,方法read()读取0个字节.这不酷.

我修改了我的代码:

    b.put("Request".getBytes());

    System.out.println("Write: " + c.write(b));

    b.flip(); //I added this line
    int i;
    while ((i = c.read(b)) != -1) {

        System.out.println("Read: " + i);
        b.clear();

    }
Run Code Online (Sandbox Code Playgroud)

实际结果:

写:1017阅读:1024阅读:44

它已经看起来更好了.谢谢你flip()!

接下来,我把缓冲区字符串"Request",这个String的长度为7,但方法write()返回1017.

什么信息方法写入渠道?

我不确定,该方法写了字符串"Request".

好的,我再次修改了我的代码:

    b.put("Request".getBytes());

    b.flip(); // I added this line
    System.out.println("Write: " + c.write(b));

    b.flip();
    int i;
    while ((i = c.read(b)) != -1) {

        System.out.println("Read: " + i);
        b.clear();

    }
Run Code Online (Sandbox Code Playgroud)

实际结果:

写:7

和代码崩溃了......

为什么?我的错误在哪里?

谢谢.

Buh*_*ndi 6

从缓冲区读取数据之前flip需要调用该方法.该方法将缓冲区重置为当前位置并将缓冲区重置为0.flip()limitposition

所以,如果你有7个字节的数据ByteBuffer,你的位置(从0开始)将是flip()7.'ing it,will make limit = 7, position = 0. 现在,可以进行阅读.

这是一个如何最好地使用的例子flip():

public static final void nioCopy(ReadableByteChannel input, WritableByteChannel output) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
    while (input.read(buffer) != -1) {
        //Flip buffer
        buffer.flip();
        //Write to destination
        output.write(buffer);
        //Compact
        buffer.compact();
    }

    //In case we have remainder
    buffer.flip();
    while (buffer.hasRemaining()) {
        //Write to output
        output.write(buffer);
    }
}
Run Code Online (Sandbox Code Playgroud)