文件下载、解压zip文件、移动文件夹、删除文件

由于IO流不熟悉带来的灾难,导致用的时候不知道用哪个流,必须记一下

1、文件下载

    /**
     *
     * @param downloadPath 下载地址
     * @param fileName 保存文件名
     * @param savePath 保存路径
     * @return
     */
    private  void download(String downloadPath,String fileName,String savePath) {
        System.out.println("正在下载"+fileName+"===============================");
        try {
            URL url = new URL(downloadPath);
            // 建立连接对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置 User-Agent 避免被拦截
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            InputStream inputStream = connection.getInputStream();
            BufferedInputStream bins = new BufferedInputStream(inputStream);
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File res = new File(file + File.separator + fileName);
            OutputStream outputStream = new FileOutputStream(res);
            BufferedOutputStream bouts = new BufferedOutputStream(outputStream);int bytesRead = 0;
            byte[] buffer = new byte[2048];
            while ((bytesRead = bins.read(buffer,0,2048)) != -1) {
                bouts.write(buffer,0,bytesRead);
            }
            bouts.flush();
            bouts.close();
            bouts.close();
            inputStream.close();
            outputStream.close();
            log.info(fileName + "文件下载成功!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.ERROR.getCode(),fileName + "文件下载失败!");
        }
    }

2、解压下载的压缩包zip文件

    /**
     * 将指定的zip文件解压到指定目录下
     * @param filePath 压缩包所在路径
     * @param zipFileName 压缩包名字
     * @param targetDirName 解压路径
     * @throws IOException
     */
    public void upzipFile(String filePath,String zipFileName, String targetDirName) {
        String zipName = filePath+File.separator+zipFileName+".zip";
        System.out.println("文件:{"+zipName+"}. 解压路径:{"+targetDirName+"}. 解压开始.");
        long start = System.currentTimeMillis();
        if (!targetDirName.endsWith(File.separator)) {
            targetDirName += File.separator;
        }
        try {
            // 根据zip文件创建ZipFile对象,此类的作用是从zip文件读取条目
//            ZipFile zip = new ZipFile(zipFile,Charset.forName("GBK"));//解决中文文件夹乱码
            ZipFile zipFile = new ZipFile(zipName, Charset.forName("GBK"));
            ZipEntry zn = null;
            String entryName = null;
            String targetFileName = null;
            byte[] buffer = new byte[4096];
            int bytes_read;
            Enumeration entrys = zipFile.entries();         // 获取ZIP文件里所有的文件条目的名字
            while (entrys.hasMoreElements()) {              // 循环遍历所有的文件条目的名字
                zn = (ZipEntry) entrys.nextElement();
                entryName = zn.getName();               // 获得每一条文件的名字
                targetFileName =  targetDirName + zipFileName + File.separator + entryName;if (zn.isDirectory()) {
                    new File(targetFileName).mkdirs();      // 如果zn是一个目录,则创建目录
                    continue;
                } else {
                    new File(targetFileName).getParentFile().mkdirs();// 如果zn是文件,则创建父目录
                }
                File targetFile = new File(targetFileName); // 否则创建文件
                System.err.println("正在创建文件:" + targetFile.getAbsolutePath());
                FileOutputStream os = new FileOutputStream(targetFile);// 打开文件输出流
                InputStream is = zipFile.getInputStream(zn);    // 从ZipFile对象中打开entry的输入流
                while ((bytes_read = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytes_read);
                }
                os.close();                             // 关闭流
                is.close();
            }
            System.out.println("文件:{"+zipName+"}. 解压路径:{"+targetDirName+"}. 解压完成.耗时:{"+(System.currentTimeMillis()-start)+"}ms.");
        } catch (IOException err) {
            System.out.println("文件:{"+zipName+"}. 解压路径:{"+targetDirName+"}. 解压结束.耗时:{"+(System.currentTimeMillis()-start)+"}ms.");
            throw new BusinessException(ResultCodeEnum.ERROR.getCode(),"解压失败!");
        }
    }

3、复制移动整个文件夹

    /**
     * 复制整个文件夹内容到目录
     *
     * @param oldPath String 原文件路径
     * @param newPath String 复制后路径
     */
    public void copyFolder(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }if (temp.isFile()) {
                    FileInputStream ins = new FileInputStream(temp);
                    BufferedInputStream bins = new BufferedInputStream(ins);
                    FileOutputStream outs = new FileOutputStream(newPath + File.separator +
                            (temp.getName()).toString());
                    BufferedOutputStream bouts = new BufferedOutputStream(outs);
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    // 开始向网络传输文件流
                    while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                        bouts.write(buffer, 0, bytesRead);
                    }
                    bouts.flush();// 刷新管道
                    ins.close();
                    bins.close();
                    outs.close();
                    bouts.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错!");
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.ERROR);
        }
    }

4、删除文件

    /**
     * 删除文件夹的内容
     * @param file
     */
    private void deleteFile(File file) {
        /**
         * File[] listFiles()
         *  返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
         */
        File[] files = file.listFiles();
        if (files!=null){//如果包含文件进行删除操作
            for (int i = 0; i <files.length ; i++) {
                if (files[i].isFile()){
                    //删除子文件
                    files[i].delete();
                }else if (files[i].isDirectory()){
                    //通过递归的方法找到子目录的文件
                    deleteFile(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }/**
     * 删除单个文件
     * @param filePath 文件路径
     */
    private void deleteFile(String filePath) {
        File deleteFile = new File(filePath);
        deleteFile.delete();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值