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("文件下载错误");
        }

    }

}
相关推荐
程序员-珍13 分钟前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
弱冠少年21 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色22 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
一般清意味……33 分钟前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
卑微求AC34 分钟前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
2401_8572979140 分钟前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
技术无疆44 分钟前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
福大大架构师每日一题1 小时前
23.1 k8s监控中标签relabel的应用和原理
java·容器·kubernetes
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
菜鸟一皓1 小时前
IDEA的lombok插件不生效了?!!
java·ide·intellij-idea