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();
            }
        }
    }
  • 相关阅读:
    RabbitMQ安装
    基于Linux的校园网破解思路和方法
    网络-0001-常见传输介质
    友情链接
    linux简史
    计算机的发展简史
    ArrayList&LinkedList&Vector区别
    Adobe Flash Player PPAPI 32.0.0.330
    ntoskrnl.exe导致蓝屏解决方法
    Git常用命令
  • 原文地址:https://www.cnblogs.com/rojas/p/5411243.html
Copyright © 2011-2022 走看看