Java文件操作总结

文件解压

 /**
     * 文件解压
     *
     * @param sourceFile 需要解压的文件路径
     * @param targetPath 目的路径
     */
    public static boolean extractFile(String sourceFile, String targetPath) {
        try {
            ZipFile zFile = new ZipFile(sourceFile);
            zFile.setFileNameCharset("GBK");

            if (!zFile.isValidZipFile()) { // 验证.zip文件是否合法,包括文件是否存在、是否为zip文件、是否被损坏等
                throw new ZipException("压缩文件不合法,可能被损坏.");
            }

            File destDir = new File(targetPath); // 解压目录
            if (destDir.isDirectory() && !destDir.exists()) {
                destDir.mkdir();
            }

            zFile.extractAll(targetPath);
        } catch (ZipException e) {
            logger.error("文件解压失败,原因:", e);
            return false;
        }

        return true;
    }

文件剪切

/**
  * 文件剪切
  *
  * @param source 源文件
  * @param target 目标文件
  */
 public static boolean fileShear(String source, String target) {
     File sourceFile = new File(source);
     boolean flag = true;

     if (!sourceFile.exists()) {
         return false;
     }

     if (!sourceFile.isDirectory()) {
         if (fileCopy(source, target)) {
             flag = sourceFile.delete();
         } else {
             flag = false;
         }

         return flag;
     } else {
         File[] files = sourceFile.listFiles();
         for (int i = 0; i < files.length; i++) {
             String filesPath = files[i].getPath().replace("\\", "/");
             if (files[i].isFile()) {
                 if (fileCopy(filesPath, filesPath.replace(source, target))) {
                     flag = files[i].delete();
                 } else {
                     flag = false;
                 }

                 if (!flag)
                     break;
             } else {
                 flag = fileShear(filesPath, filesPath.replace(source, target));

                 if (!flag)
                     break;
             }
         }

         if (!flag)
             return false;
         // 删除当前目录
         if (sourceFile.delete()) {
             return true;
         } else {
             return false;
         }
     }
 }

文件夹删除

 /**
     * 文件夹删除
     *
     * @param filePath 需要删除的文件夹路径
     */
    public static boolean deleteFiles(String filePath) {
        boolean flag = true;
        File dirFile = new File(filePath);

        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }

        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                File file = new File(files[i].getAbsolutePath());
                flag = file.delete();
                if (!flag)
                    break;
            } else {
                flag = deleteFiles(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }

        if (!flag)
            return false;
        // 删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

文件打包

 /**
     * 文件打包
     *
     * @param filePathList 需要打包的文件路径集合
     * @param targetPath   目的路径
     * @param password     打包密码
     */
    public static boolean collectFiles(List<String> filePathList, String targetPath, String password) {
        try {
            File targetPathParent = new File(new File(targetPath).getParent());
            if (!targetPathParent.exists()) {
                targetPathParent.mkdirs();
            }

            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_STORE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);
            if (password != null && !password.equals("")) {
                parameters.setEncryptFiles(true);
                parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
                parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
                parameters.setPassword(password);
            }

            ZipFile zipFile = new ZipFile(targetPath);
            zipFile.setFileNameCharset("gbk");

            for (String ss : filePathList) {
                File file = new File(ss);
                if (file.exists() && file.isDirectory()) {
                    zipFile.addFolder(file, parameters);
                } else if (file.exists() && file.isFile()) {
                    zipFile.addFile(file, parameters);
                }
            }
        } catch (ZipException e) {
            logger.error("文件打包失败,原因:", e);
            return false;
        }

        return true;
    }

下载打包的文件

 /**
     * 下载打包的文件
     *
     * @param file
     * @param response
     * @param isDelete 是否删除源文件
     */
    public static void downloadZip(File file, HttpServletResponse response, boolean isDelete) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        boolean boo = false;

        try {
            response.reset();
            response.setCharacterEncoding("ISO8859-1");
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/octet-stream");
            response.setHeader("Connection", "close");
            response.setContentLength((int) file.length());

            bis = new BufferedInputStream(new FileInputStream(file.getPath()));
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] b = new byte[10240];
            int len = 0;
            while ((len = bis.read(b, 0, b.length)) != -1) {
                bos.write(b, 0, len);
            }

            bos.flush();
            boo = true;
        } catch (Exception e) {
            boo = false;
        } finally {
            try {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                boo = false;
            }

            if (boo && isDelete) {
                file.delete();
            }
        }
    }

文件拷贝

 /**
     * 文件拷贝
     *
     * @param f1Path 源路径
     * @param f2Path 目标路径
     */
    public static boolean fileCopy(String f1Path, String f2Path) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f1 = null;
        File f2 = null;

        int outputSize = 1024000;// 默认1M
        boolean boo = false;

        try {
            f1 = new File(f1Path);
            f2 = new File(f2Path);

            File pfile = new File(f2.getParent());
            if (!pfile.exists()) {
                pfile.mkdirs();
            }

            if (f1.length() > 104857600) {
                outputSize = 10240000; // 文件大于100M,修改outputSize为10240000
            }

            FileInputStream fis = new FileInputStream(f1);
            FileOutputStream fos = new FileOutputStream(f2);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] b = new byte[outputSize];
            int len = 0;
            while ((len = bis.read(b, 0, b.length)) != -1) {
                bos.write(b, 0, len);
            }

            bos.flush();
            boo = true;
        } catch (Exception e) {
            boo = false;
            logger.error("文件" + f1Path + "拷贝失败,原因:", e);
        } finally {
            try {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                boo = false;
                e.printStackTrace();
            }

            if (boo) {
                // 修改时间戳
                boo = f2.setLastModified(f1.lastModified());
            }
        }

        return boo;
    }

    /**
     * 文件拷贝 20181110
     *
     * @param f1File 源路径
     * @param f2File 目标路径
     */
    public static boolean fileCopyNew(File f1File, File f2File) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        int outputSize = 1024000;// 默认1M
        boolean boo = false;

        try {
            File pfile = f2File.getParentFile();
            if (!pfile.exists()) {
                pfile.mkdirs();
            }
            pfile = null; //回收对象

            if (f1File.length() > 104857600) {
                outputSize = 10240000; // 文件大于100M,修改outputSize为10240000
            }

            FileInputStream fis = new FileInputStream(f1File);
            FileOutputStream fos = new FileOutputStream(f2File);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] b = new byte[outputSize];
            int len = 0;
            while ((len = bis.read(b, 0, b.length)) != -1) {
                bos.write(b, 0, len);
            }

            bos.flush();
            boo = true;
        } catch (Exception e) {
            boo = false;
            logger.error("文件" + f1File.getPath() + "拷贝失败,原因:", e);
        } finally {
            try {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                boo = false;
                e.printStackTrace();
            }

            if (boo) {
                // 修改时间戳
                boo = f2File.setLastModified(f1File.lastModified());
            }
        }

        return boo;
    }

文件大小格式化(大小转化为T G KB)

  /**
     * 文件大小格式化
     *
     * @param length 文件大小
     */
    public static String fileSizeFormat(long length) {
        DecimalFormat df = new DecimalFormat("#0.0");
        float size = (float) length / 1024;
        String sumFilesize = "";

        if (size >= 0 && size < 1) {
            sumFilesize = length + " B";
        } else if (size >= 1 && size < 1024) {
            sumFilesize = df.format(size) + " K";
        } else if (size >= 1024) {
            size = size / 1024;
            if (size >= 1 && size < 1024) {
                sumFilesize = df.format(size) + " M";
            } else if (size >= 1024 && size < 1048576) {
                size = size / 1024;
                sumFilesize = df.format(size) + " G";
            } else if (size >= 1048576) {
                size = size / 1024 / 1024;
                sumFilesize = df.format(size) + " T";
            }
        }

        return sumFilesize;
    }

获取文件后缀名

  /**
     * 获取文件后缀名
     */
    public static String getFileExtension(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }

判断是否有汉字

/**
     * @return
     * @Description 判断是否有汉字
     * @Param
     **/
    public static boolean isChinese(String countname) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(countname);
        if (m.find()) {
            return true;
        }
        return false;
    }

获取文件最后修改时间

  //最后修改时间

//       lastModified获取最后修改时间的时间戳,DateUtils.stampToDate转化时间格式
   File f1 = new File(s1);
f1.lastModified();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值