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

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

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值