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();
            }
        }
    }
  • 相关阅读:
    数组列简介
    linq的使用
    StringBuilder对象
    使用类来继承接口
    设置函数库并引用
    循环语句
    cut和paste用法
    uniq用法
    shell中数组的应用
    委派
  • 原文地址:https://www.cnblogs.com/rojas/p/5411243.html
Copyright © 2011-2022 走看看