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

本篇内容主要讲解“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完成文件复制”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!