java使用nio读取复制文件

下面是测试代码,实际情况请以业务需求为准

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Test
    public void nIOReadTextFile() {
        String filePath = "C:\\Users\\virgil\\Desktop\\新建文本文档.txt";
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(filePath, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = fileChannel.read(byteBuffer);
            while (read != -1) {
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    System.out.print((char) byteBuffer.get());
                }
                byteBuffer.compact();
                read = fileChannel.read(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    @Test
    public void nioCopyFileTest() {
//        nioCopyFile("G:\\nIO Copy\\1.txt", "G:\\nIO Copy\\2.txt");
        nioCopyFile("C:\\Users\\virgil\\Pictures\\Saved Pictures\\616ad2a19e4ac0d5ad82530e0b00101a.jpg", "G:\\nIO Copy\\1.jpg");
    }


    public void nioCopyFile(String readFilePath, String copyFileEndPath) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(new File(readFilePath)).getChannel();
            outChannel = new FileOutputStream(new File(copyFileEndPath)).getChannel();
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inChannel != null) {
                    inChannel.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (outChannel != null) {
                    outChannel.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值