利用FileChannel实现文件文件复制和读写

本文介绍了如何利用Java的FileChannel进行大文件的复制和读写操作,强调其在处理大文件时的性能优势。通过建立FileChannel并结合ByteBuffer缓存区,可以有效地读写文件。在读写过程中,运用了ByteBuffer的flip()方法进行数据反转,以实现从写模式到读模式的转换,使得数据处理更加高效。
摘要由CSDN通过智能技术生成

FileChannel所实现的是管间通信,与普通的读写不同在进行大文件的读写上有很大的优势;
首先是管道的建立,可以通过I/O流来建立FileChannel;下面是利用通道进行文件复制

public static boolean copy(File start,File end)  {
        try(
                FileInputStream in = new FileInputStream(start);
                FileOutputStream out = new FileOutputStream(end);
                FileChannel fIn  = in.getChannel();
                FileChannel fOut  = out.getChannel();
                ){
            fIn.transferTo(0, fIn.size(),fOut);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

如果要利用FileChannel进行读写,就需要用ByteBuffer类建立一个缓存区,可以通过Charset来指定字节码,然后对缓存区进行解码

public static String read(FileChannel fileChannel, Charset charset) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        StringBuilder stringBuilder = new StringBuilder();
        fileChannel.read(charset.encode("UTE-8
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值