简体   繁体   English

跳过字节Java NIO SocketChannel

[英]Skipping bytes Java NIO SocketChannel

Let's assume I have SocketChannel is waiting for read. 假设我有SocketChannel正在等待读取。 I don't want to read the first K bytes (as in, I don't want to copy them to a byte buffer, just skip them). 我不想读取前K个字节(例如,我不想将它们复制到字节缓冲区,只需跳过它们)。

Is there anyway of doing so? 反正有这样做吗? there is no skip() method available. 没有可用的skip()方法。

I'm not sure if this is what you want to achieve, or even if it works as you want to, but you can get a Socket and then an InputStream from it. 我不确定这是否是您想要实现的,或者即使它可以按您希望的那样工作,但是您可以从中获取一个Socket ,然后再获取一个InputStream

Since you want to skip bytes, seems that work with I/O streams is the best solution. 由于您想跳过字节,因此似乎最好使用I / O流。

    SocketChannel sock = SocketChannel.open();
    sock.connect(new InetSocketAddress("your addres or something", 80));

    InputStream ins = sock.socket().getInputStream();

    //Skip here
    ins.skip(5);

Edit 编辑

No, you cannot reuse what you have consumed with the input stream. 不,您不能重复使用输入流中已消耗的内容。

By the way, could you be more precise with "The allocation" problem? 顺便说一句,您能否更精确地处理“分配”问题? You can pipe the InputStream, so why do you say that you have to allocate a buffer? 您可以通过管道传输InputStream,为什么要说必须分配一个缓冲区呢? What is the target at the end? 最后的目标是什么?

Edit 2 编辑2

There's an example that does not need to allocate K bytes 有一个示例,不需要分配K个字节

        ins.skip(1);

        ArrayList<Byte> bts = new ArrayList<>();

        int last = 0;
        while (last != -1) {
            last = in.read();
            bts.add((byte)last);
        }
        System.out.println(bts.stream().map(b -> new String(new byte[]{b.byteValue()})).collect(Collectors.joining()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM