对文件的处理工具类 实现了简单的文件操作

import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件相关工具类
 *
 * Created by spring on  2018/9/3
 */
public class FileUtil {

    /**
     * 生成文件名
     *

     * @param fileName
     * @return
     */
    public  static String getFileName(String fileName){
        if(StringUtils.isBlank(fileName)   ){
            return null;
        }
        String returnFileName =  fileName+"_"+Calendar.getInstance().getTimeInMillis()+".xlsx";
        return returnFileName;
    }

    /**
     * 生成文件目录
     *
     * @param path
     * @return
     */
    public static String getFilePath(String path){
        if(StringUtils.isBlank(path)){
            return  null;
        }
        Calendar cal = Calendar.getInstance();
        int week =cal.get(Calendar.DAY_OF_WEEK);
        Date time = cal.getTime();
        String timeMm = DateUtil.format(time, "yyyyMM");
        String filePath = path+"report"+"/"+timeMm+"_"+week+"/";
        return filePath;
    }
    /**
     * 生成文件目录 并创建文件夹
     *
     * @param path
     * @return
     */
    public static String getAndMkFilePath(String path){
        if(StringUtils.isBlank(path)){
            return  null;
        }
        path= getFilePath(path);
        File file = new File(path);
        //判断目录是否存在 不存在则创建
        if(!file.exists()){
            file.mkdirs();
        }
        return path;
    }

    /**
     * 生成文件以及目录  并创建相关文件
     * 根据根目录生成规则的文件路径和文件,文件路径遵循无则创建,文件有则删除重建,无则生成
     *
     * @param path 根目录
     * @param fileName  文件原名

     * @return
     * @throws IOException
     */
    public  static String getFilePathAndName(String path,String fileName) throws IOException {
        if(StringUtils.isBlank(path) || StringUtils.isBlank(fileName)    ){
            return  null;
        }
        //获得文件名
        fileName = getFileName( fileName);
        //获得文件全路径
        path = getFilePath(path);

       String  pathName = path+fileName;
        File file = new File(path);
        //判断目录是否存在 不存在则创建
        if(!file.exists()){
            file.mkdirs();
        }
        //判断文件是否存在
        file = new File(pathName);
        //返回文件全路径和文件
        if (file.exists()) {
            file.delete();// 删除文件
        }
        file.createNewFile();
        return pathName;
    }

    /**
     * 文件清除
     *
     * @param dir 上传文件为目录下文件
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }

    /**
     * 删除文件修改时间大于7的文件
     *
     * @param dir 上传文件为目录下文件
     * @return
     */
    public static boolean deleteDirFile(File dir) throws IOException {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                if(new File(dir, children[i]).isDirectory()){
                    deleteDirFile(new File(dir, children[i]));
                }else{
                    String canonicalPath = new File(dir, children[i]).getCanonicalPath();
                    Date createTime2 = getCreateTime2(canonicalPath);
                    Integer dayBetween = DateUtil.getDayBetween(createTime2, Calendar.getInstance().getTime());
                    if(dayBetween > 7){
                        boolean success = deleteDir(new File(dir, children[i]));
                        if (!success) {
                            return false;
                        }
                    }
                }
            }
        }
        // 目录此时为空,可以删除
        return true;
    }







    private static Date getCreateTime2(String fullFileName) {
        Path path = Paths.get(fullFileName);
        BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr;
        try {
            attr = basicview.readAttributes();
            Date createDate = new Date(attr.creationTime().toMillis());
            return createDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
     * @param sourceFilePath :待压缩的文件路径 路径不是文件
     * @param zipFilePath :压缩后存放路径
     * @param fileName :压缩后文件的名称  不做重复判断  重复报错
     * @return
     */
    public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){
        boolean flag = false;
        File sourceFile = new File(getFilePath(sourceFilePath));
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if(sourceFile.exists() == false){
            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");
            sourceFile.mkdir(); // 新建目录
        }
        try {
            File zipFile = new File(zipFilePath + "/" + fileName +".zip");
            if(zipFile.exists()){
                System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");
            }else{
                File[] sourceFiles = sourceFile.listFiles();
                if(null == sourceFiles || sourceFiles.length<1){
                    System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
                }else{
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024*10];
                    for(int i=0;i<sourceFiles.length;i++){
                        //创建ZIP实体,并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        zos.putNextEntry(zipEntry);
                        //读取待压缩的文件并写进压缩包里
                        fis = new FileInputStream(sourceFiles[i]);
                        bis = new BufferedInputStream(fis, 1024*10);
                        int read = 0;
                        while((read=bis.read(bufs, 0, 1024*10)) != -1){
                            zos.write(bufs,0,read);
                        }
                    }
                    flag = true;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //关闭流
            try {
                if(null != bis) bis.close();
                if(null != zos) zos.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return flag;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值