IO_文件复制与剪切

复制

@Test
    public void FileCopy() {
        String fromPath = "E:\\IO_CopyFrom\\alan.txt";
        String toPath = "E:\\IO_CopyTo\\alan.txt";

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(fromPath);
            fileOutputStream = new FileOutputStream(toPath);
            //定义一个字节数组提高读取效率
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //读取到字节数据后马上进行写入
                //一定要使用(byte[] b,int off,int len) 因为数据总字节数未必可以被字节数组容量整除
                fileOutputStream.write(buf, 0, readLen);
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

剪切

实质上在复制的基础上将原文件删除,即为剪切

注:删除命令需要在流关闭后使用,否则文件处于被占用状态,无法进行删除

        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //在复制完成后进行原文件删除 即为剪切
        //删除命令需要在流关闭后使用 否则文件处于被占用状态 无法进行删除
        del();
    }

    @Test
    public void del() {
        String filePath = "E:\\IO_CopyFrom\\alan.txt";
        File file = new File(filePath);
        file.delete();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值