Java磁盘与程序之间的关系

5 篇文章 0 订阅
1 篇文章 0 订阅

主要发生在文件处理中,比如使用I/O流读写文件时。程序会影响到磁盘使用率。

public class TestDisk {
    public static void main(String[] args) throws IOException {
    // 123.zip是源文件,d,是目标盘
         copyFileByBuf("E:\\123.zip","D:");
    }

    public static void copyFileByBuf(String srcPath,String destDirPath) throws IOException {
        //源文件
        File srcFile = new File(srcPath);
        //目标文件夹
        File destDirFile = new File(destDirPath);
        if(!destDirFile.exists()){
            destDirFile.mkdirs();
        }
        //目标文件
        File descFile = new File(destDirPath+File.separator+srcFile.getName());
        //如果此处有检查性异常可以使用Alt+Enter快速完成代码
        //字节输入流
        FileInputStream inputStream = new FileInputStream(srcFile);
        //对输入流包装
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        //字节输出流
        FileOutputStream outputStream = new FileOutputStream(descFile);
        //对输出流进行包装
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

        //开辟内存,存储从流中读取到的数据
        byte[] buf = new byte[1024*16];
        //开始读取数据 length为实际读取到的字节个数,如果读到文件结尾,则返回-1
        int length = bufferedInputStream.read(buf);
        while(length != -1){
            //向目标文件中写数据
            bufferedOutputStream.write(buf,0,length);
            length = bufferedInputStream.read(buf);
        }
        //释放资源
        bufferedInputStream.close();
        //输出流关闭前切记要流中的缓存数据给推送出去
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值