zoukankan      html  css  js  c++  java
  • java nio channel

    //Listing 7-1. Copying Bytes from an Input Channel to an Output Channel
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.channels.WritableByteChannel;
    
    public class ty {
        public static void main(String[] args) {
            ReadableByteChannel src = Channels.newChannel(System.in);
            WritableByteChannel dest = Channels.newChannel(System.out);
            try {
                copy(src, dest); // or copyAlt(src, dest);
            } catch (IOException ioe) {
                System.err.println("I/O error: " + ioe.getMessage());
            } finally {
                try {
                    src.close();
                    dest.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    
        static void copy(ReadableByteChannel src, WritableByteChannel dest)
                throws IOException {
            ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
            while (src.read(buffer) != -1) {
                buffer.flip();
                dest.write(buffer);
                buffer.compact();
            }
            buffer.flip();
            while (buffer.hasRemaining())
                dest.write(buffer);
        }
    
        static void copyAlt(ReadableByteChannel src, WritableByteChannel dest)
                throws IOException {
            ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
            while (src.read(buffer) != -1) {
                buffer.flip();
                while (buffer.hasRemaining())
                    dest.write(buffer);
                buffer.clear();
            }
        }
    }
  • 相关阅读:
    从TCP三次握手说起——浅析TCP协议中的疑难杂症
    动态绑定是如何实现的?
    C++对象的内存模型
    C/C++关键字
    libevent库介绍--事件和数据缓冲
    libevent编程疑难解答
    大型工程多个目录下的Makefile写法
    C++中的RAII机制
    C++中的智能指针
    二叉树的非递归遍历
  • 原文地址:https://www.cnblogs.com/rojas/p/5411243.html
Copyright © 2011-2022 走看看