IO流必知必会(20)——Channel

Channel与普通的流存在的差别是:Channel可以将文件的全部或者部分直接映射成为Buffer,程序不能直接访问Channel中的数据(读、写),只能通过Buffer来与Channel交互。

Channel是通过其功能进行划分的,如:DatagramChannel(UDP网络通信)、Pipe.sinkChannel(线程通信)......

    public static void main(String[] args) {
        File file = new File("src/threaddemo/FileChannelTest.java");
        try (FileChannel inChannel = new FileInputStream(file).getChannel();
                FileChannel outChannel = new FileOutputStream("test.txt")
                        .getChannel()) {
            MappedByteBuffer buff = inChannel.map(
                    FileChannel.MapMode.READ_ONLY, 0, file.length());
            Charset charset = Charset.forName("GBK");
            outChannel.write(buff);
            buff.clear();
            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer = decoder.decode(buff);
            System.out.println(charBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
java全栈日日学 文章被收录于专栏

java全栈每日必学,不要高估自己一年能做的事,不要低估自己十年能做的事

全部评论

相关推荐

05-10 16:48
门头沟学院 Java
程序员小白条:主要原因,投递太晚了,快手应该早点溜了,你都从去年9月开始的,半年也差不多3月跑路了,这样的话,至少有5个以上的面试机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务