java文件查看大小,压缩,文件下载工具类

bash 复制代码
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName: FileSpaceUtil
 * @Description:
 * @Author: 
 * @Date: 
 **/
@Slf4j
public class FileSpaceUtil {
    //查看磁盘空间总大小
    public static double getTotalSpace(){
        File file = new File("/");
        long totalSpace = file.getTotalSpace();
        double space = totalSpace * 1.0 / (1024 * 1024 * 1024);
        BigDecimal two = new BigDecimal(space);
        double size=two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        return size;
    }

    //查看磁盘空间可用内存
    public static double getUseSpace(){
        File file = new File("/");
        long usableSpace = file.getUsableSpace();
        double space = usableSpace*1.0/(1024 * 1024 * 1024);
        BigDecimal two = new BigDecimal(space);
        double size=two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        return size;
    }

    public static double  getFolderSize(File folder){
        long length= FileUtils.sizeOfDirectory(folder);
        BigDecimal two = new BigDecimal(length*1.0/(1024*1024*1024));
        double size=two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

        return size;
    }

    public static String getFileSize(MultipartFile file) {
        long fileBytes = file.getSize();
        double size;
        String unit;
        if (fileBytes < 1024 * 1024) {
            size = fileBytes / 1024.0;
            unit = "KB";
        } else {
            size = fileBytes / 1024.0 / 1024;
            unit = "MB";
        }
        BigDecimal bigDecimal = new BigDecimal(size);
        double v = bigDecimal.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return v + unit;
    }
    public static String getFileSize(Long fileBytes) {
        double size;
        String unit;
        if (fileBytes < 1024 * 1024) {
            size = fileBytes / 1024.0;
            unit = "KB";
        } else {
            size = fileBytes / 1024.0 / 1024;
            unit = "MB";
        }
        BigDecimal bigDecimal = new BigDecimal(size);
        double v = bigDecimal.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return v + unit;
    }


    /**
     * 多目录文件压缩
     * @param targetDir 要压缩的文件夹
     * @param compressFilePath 压缩文件路径,如果null默认为文件名称
     * @return
     */
    public static boolean zip(String targetDir, String compressFilePath){
        boolean ret=false;
        try{
            File sourceFile = new File(targetDir);
            if(StringUtils.isBlank(compressFilePath)){
                compressFilePath = sourceFile.getParentFile().getAbsolutePath() + File.separator + sourceFile.getName() + ".zip";
            }
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(compressFilePath));
            ret=zipToFile(sourceFile, sourceFile.getName(), zipOutputStream);
            zipOutputStream.close();
            return ret;
        }catch (Exception e){
            log.error("压缩文件异常!", e);
            return  ret;
        }
    }


    private static boolean zipToFile(File sourceDir, String zipDirName, ZipOutputStream targetZipOut){
        boolean ret=false;
        if(!sourceDir.exists()){
            log.debug("待压缩的目录"+sourceDir.getName()+"不存在");
            return ret;
        }

        File[] files = sourceDir.listFiles();
        if(files == null || files.length ==0){
            return ret;
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        byte[] byteArray = new byte[1024*10];

        try{
            for (File file : files) {
                if (file.isFile()) {
                    log.debug("开始压缩:{}", file.getAbsoluteFile());
                    ZipEntry zipEntry = new ZipEntry(zipDirName + File.separator + file.getName());
                    targetZipOut.putNextEntry(zipEntry);
                    //读取待压缩的文件并写进压缩包里
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis, 1024 * 10);
                    int read;
                    while ((read = bis.read(byteArray, 0, 1024 * 10)) != -1) {
                        targetZipOut.write(byteArray, 0, read);
                    }
                    //如果需要删除源文件,则需要执行下面2句
                    //fis.close();
                    //fs[i].delete();
                } else if (file.isDirectory()) {
                    log.debug("进入目录:{}", file.getAbsoluteFile());
                    zipToFile(file, zipDirName + File.separator + file.getName(), targetZipOut);
                }
            }//end for
            ret=true;
            return ret;
        }catch  (IOException e) {
            log.error("打包异常!",e);
            return ret;
        } finally{
            //关闭流
            try {
                if(null!=bis) bis.close();
                if(null!=fis) fis.close();
            } catch (IOException e) {
                log.error("打包关闭流异常!",e);
            }
        }
    }


    /***
     * 将String转文件文件
     * @param musicInfo
     * @param fileName
     * @param filePath
     * @param type 文件类型:例如:".txt/.log"
     * @throws IOException
     */
    public static void writeToText(String musicInfo, String fileName,String filePath,String type) throws IOException {
        // 生成的文件路径
        String path = filePath + fileName + type;
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        // write 解决中文乱码问题
        // FileWriter fw = new FileWriter(file, true);
        OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(musicInfo);
        bw.flush();
        bw.close();
        fw.close();

    }




    public static String fileToString(String path){
        try {
            File file =new File(path);
            if (!file.exists()){
                throw new Error("error");
            }
            InputStreamReader read = new InputStreamReader(new FileInputStream(file),"utf8");
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            String tempTxt = "";
            while((lineTxt = bufferedReader.readLine()) != null){
                //  System.getProperty("line.separator")   为换行符号
                tempTxt+=lineTxt + System.getProperty("line.separator");
            }
            read.close();
            return tempTxt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件下载
     * @param response
     * @param path 文件路径
     */
    public static  void download(HttpServletResponse response,String path) {
        log.info("下载文件路径"+path);
        String fileName=path.substring(path.lastIndexOf("/")+1,path.length());

        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            File file = new File(path);
            if(!file.exists()){
                response.setStatus(HttpStatus.NOT_FOUND.value());
                return;
            }
            FileInputStream fi=new FileInputStream(file);
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            IoUtil.copy(fi, response.getOutputStream());
        } catch (IOException e) {
            log.info("文件下载错误");
        }

    }

}
相关推荐
明月看潮生6 分钟前
青少年编程与数学 02-003 Go语言网络编程 15课题、Go语言URL编程
开发语言·网络·青少年编程·golang·编程与数学
雷神乐乐10 分钟前
File.separator与File.separatorChar的区别
java·路径分隔符
小刘|14 分钟前
《Java 实现希尔排序:原理剖析与代码详解》
java·算法·排序算法
南宫理的日知录17 分钟前
99、Python并发编程:多线程的问题、临界资源以及同步机制
开发语言·python·学习·编程学习
逊嘘33 分钟前
【Java语言】抽象类与接口
java·开发语言·jvm
Half-up36 分钟前
C语言心型代码解析
c语言·开发语言
morris13140 分钟前
【SpringBoot】Xss的常见攻击方式与防御手段
java·spring boot·xss·csp
Source.Liu1 小时前
【用Rust写CAD】第二章 第四节 函数
开发语言·rust
monkey_meng1 小时前
【Rust中的迭代器】
开发语言·后端·rust
余衫马1 小时前
Rust-Trait 特征编程
开发语言·后端·rust