温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java8中怎么利用通道FileChannel完成文件复制

发布时间:2021-11-24 16:48:27 来源:亿速云 阅读:352 作者:iii 栏目:大数据

本篇内容主要讲解“java8中怎么利用通道FileChannel完成文件复制”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java8中怎么利用通道FileChannel完成文件复制”吧!

一、通道(channel):用于源节点与目标节点的链接,在java nio 中负责缓冲区中的数据的传输,Channel本省不存储数据,因此需要配合缓冲区进行传输*二、通道的主要实现类*      java.nio.channel.Channel 接口:*          |--FIleChannel*          |--SocketChannel*          |--ServerSocketChannel*          |--DatagramChannel** 三、获取通道*  1.java 针对支持通道的类提供了 getChannel()方法*         本地IO:*         FileInputStream/FileOutputStream*         RandomAccessFile**         网络IO:*         Socket
*         ServerSocket
*         DatagramSocket
*   2.在JDK 1.7中的NIO.2 针对各个通道提供了静态方法 open()**   3.在JDK 1.7 中的NIO.2 的Files 工具类的 newByteChannel()public class TestChannel {// 1.利用通道完成文件复制    @Test    public void test1(){
        FileInputStream inputStream= null;        FileOutputStream outputStream= null;        FileChannel inChannel= null;        FileChannel outChannel= null;        try {
            inputStream = new FileInputStream("1.jpg");            outputStream = new FileOutputStream("2.jpg");            // ① 获取通道            inChannel = inputStream.getChannel();            outChannel = outputStream.getChannel();            // ② 分配指定大小的缓冲区            ByteBuffer byteBuffer=ByteBuffer.allocate(1024);            // ③ 将通道中的数据存入缓冲区            while (inChannel.read(byteBuffer) !=-1){
                byteBuffer.flip(); // 切换读取数据模式                // ④ 将缓冲区中的数据写入目标通道中                outChannel.write(byteBuffer);                byteBuffer.clear();            }
        } catch (IOException e) {
            e.printStackTrace();        } finally {if (outChannel!=null){try {
                    outChannel.close();                } catch (IOException e) {
                    e.printStackTrace();                }
            }if (inChannel!=null){try {
                    inChannel.close();                } catch (IOException e) {
                    e.printStackTrace();                }
            }if (outputStream!=null){try {
                    outputStream.close();                } catch (IOException e) {
                    e.printStackTrace();                }
            }if (inputStream!=null){try {
                    inputStream.close();                } catch (IOException e) {
                    e.printStackTrace();                }
            }
        }

    }
}

到此,相信大家对“java8中怎么利用通道FileChannel完成文件复制”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI