操作文件:对文件进行的一些操作、复制、移动、改名、删除、排序等的文件工具类

package cn.dreamit.p2047.module_200730185526Po0wk3EgoVQLuKxFyNJ.utils;

import cn.dreamit.dreamweb.common.constant.SeparatorConstants;
import cn.dreamit.dreamweb.persistence.dao.EntityDao;
import cn.dreamit.p1000.module.metadata.util.ExportExcelUtil;
import cn.dreamit.p1000.module.orginization.entity.Orginization;
import cn.dreamit.p1000.module.userinfo.entity.User;
import cn.dreamit.p1000.util.SuperKit;
import cn.dreamit.p1001.module_190426200952aK76Tb6iwS0qF3Bz5Ap.constants.ContactsConstants;
import cn.dreamit.p2047.module_200730185526Po0wk3EgoVQLuKxFyNJ.entity.RegistForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import xsf.data.DBManager;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileUtils {

    private static final Logger logger=LoggerFactory.getLogger(FileUtils.class);


    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如:c:/fqf
     * @param newPath String 复制后路径 如:f:/fqf/ff
     * @return boolean
     */
    public static 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 input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            logger.error("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            logger.error("复制单个文件失败");
        }
    }

    /**
     * @param path 文件夹路径
     * @description: 通过文件路径,修改该路径下所有文件的名字
     * @return:
     * @author:
     * @date
     */
    public static  void changeFileName(String path, String fileCode,Map<String,String> oldAndNewFileNames) {
        String unitId= SuperKit.getTenantUnitId();
        String unitName = DBManager.getFieldStringValue("select org_name from g_organize where id='" + unitId + "'");
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
            } else {
                //先将文件按照zip、xml、pdf排序
                List<File> fileList = getFiles(files);
                for (int i = 0; i < fileList.size(); i++) {
                    String filePath = fileList.get(i).getAbsolutePath();
                    String oldFileName = fileList.get(i).getName();
                    String newFileName = fileCode + SeparatorConstants.UNDER_LINE + (i + 1) + filePath.substring(filePath.lastIndexOf("."));
                    File oriFile = new File(filePath);
                    if (newFileName.endsWith(".zip")){
                        oldAndNewFileNames.put(newFileName,"浦东新区"+unitName+"单位电子文件归档信息包");
                    }else
                    if (newFileName.endsWith(".xml")){
                        oldAndNewFileNames.put(newFileName,oldFileName.replaceAll(".xml","")+"XML文件");
                    }else{
                        oldAndNewFileNames.put(newFileName,oldFileName.replaceAll(".pdf",""));
                    }
                    oriFile.renameTo(new File(path + SeparatorConstants.FILE_SEPARATOR_CHAR + newFileName));
                }
            }
        } else {
            logger.error("该路径不存在");
        }
    }

    /**
     * 根据传进来的File[]数组重新排序。按照zip、xml、pdf排序
     * @param files
     * @return
     */
    private static List<File> getFiles(File[] files){
        List<File> fileList = Arrays.asList(files);
        List<File> newFileList=new ArrayList<>();
         fileList.stream().forEach(file -> {
             if (file.getName().endsWith(".zip")){
                 newFileList.add(file);
             }
         });
        fileList.stream().forEach(file -> {
            if (file.getName().endsWith(".xml")){
                newFileList.add(file);
            }
        });
        fileList.stream().forEach(file -> {
            if (file.getName().endsWith(".pdf")){
                newFileList.add(file);
            }
        });
        return newFileList;
    }

    /**
     * 清除
     *
     * @param filePath
     */
    public static void clearFiles(String filePath) {
        File scFileDir = new File(filePath);
        File TrxFiles[] = scFileDir.listFiles();
        if (TrxFiles.length!=0){
            for (File curFile : TrxFiles) {
                curFile.delete();
            }
        }
        scFileDir.delete();
    }

    /**
     * 删除某个文件夹下所有文件
     * @param url
     * @return
     */
    public static boolean deleteFolder(String url) {
        File file = new File(url);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            file.delete();
            return true;
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                String root = files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
                //System.out.println(root);
                deleteFolder(root);
            }
            file.delete();
            return true;
        }
    }

//将大路径名作为建、里面各个路径作为value存为list集合
    public static void recursion(String root, List<String> vecFile, Map<String,List<String>> vecFileMap,String mapKey) {
        File file = new File(root);
        File[] subFile = file.listFiles();
        for (int i = 0; i < subFile.length; i++) {
            if (subFile[i].isDirectory()) {
                List<String> vecFileList=new ArrayList<>();
                String key=subFile[i].getName();
                recursion(subFile[i].getAbsolutePath(), vecFileList,vecFileMap,key);
            } else {
                String filename = subFile[i].getName();
                if (!(filename.endsWith(".xls")||filename.endsWith(".xls")||filename.endsWith(".mdb"))){
                    vecFile.add(filename);
                }
            }
        }
        vecFileMap.put(mapKey,vecFile);
    }

    /**
     * 获取文件大小
     * @param filename
     * @return
     */
    public static String getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
            return "-1";
        }
        return String.valueOf(file.length());
    }

    /**
     * 根据文件路径生成SHA-256数字摘要
     * @param filePath
     * @return
     */
    public static String getSHA(String filePath) {
        MessageDigest md = null;
        String res = "";
        try {
            md = MessageDigest.getInstance("SHA-256");
            File file = new File(filePath);
            long len = file.length();
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            byte[] buff = new byte[(int) len];
            int num = 0;
            try {
                num = in.read(buff);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            md.update(buff, 0, num);
            byte[] out = md.digest();


            for (byte b : out) {
                res += String.format("%02x", b);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return res;
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值