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

    }

}
相关推荐
爪哇学长2 分钟前
双指针算法详解:原理、应用场景及代码示例
java·数据结构·算法
Dola_Pan6 分钟前
C语言:数组转换指针的时机
c语言·开发语言·算法
ExiFengs6 分钟前
实际项目Java1.8流处理, Optional常见用法
java·开发语言·spring
paj1234567898 分钟前
JDK1.8新增特性
java·开发语言
IT古董15 分钟前
【人工智能】Python在机器学习与人工智能中的应用
开发语言·人工智能·python·机器学习
繁依Fanyi19 分钟前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse
慧都小妮子30 分钟前
Spire.PDF for .NET【页面设置】演示:打开 PDF 时自动显示书签或缩略图
java·pdf·.net
m512734 分钟前
LinuxC语言
java·服务器·前端
IU宝39 分钟前
C/C++内存管理
java·c语言·c++
湫ccc39 分钟前
《Python基础》之pip换国内镜像源
开发语言·python·pip