java file工具类

2 篇文章 0 订阅
1 篇文章 0 订阅
import cc.mrbird.febs.common.entity.FebsConstant;	// 常亮
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {

    /**
     *  读取文件的方法,
     *  把数据存到list当中返回
     * @param file  读取文件路径
     * @return List<String>
     */
    public static List<String> getData(File file) throws IOException {
        List<String> list = new ArrayList<String>();
        if (!file.exists()) throw new FileNotFoundException(file + "不存在!");
        FileReader fr = new FileReader(file);
        @SuppressWarnings("resource")               //去掉没必要警告
        BufferedReader br = new BufferedReader(fr); //创建缓存区,提高读取效率
        String str;
//    		br.readLine();   //除去第一行  /*看情况使用*/
        while((str = br.readLine())!=null) {
            list.add(str);
        }
        br.close();
        fr.close();
        return list;
    }

    /**
     * 写入文件,按List<String>列表写入数据
     * @param file 要写入的文档名
     * @param data  要写入的数据list
     *        每次写入文件都会删除原来的内容
     */
    public static void writeData(File file,List<String> data) throws IOException {
        FileWriter fw;
        if(file.exists()) {
            file.delete();
        }
        file.createNewFile();
        fw = new FileWriter(file,true);     //创建io流,写入文档
        @SuppressWarnings("resource")
        BufferedWriter bw = new BufferedWriter(fw); //创建缓存区,提高写入效率
        for(String str:data) {
            bw.write(str+"\n");	//写入数据
            bw.flush();             // 刷新缓存区
        }
        bw.close();     // 关闭缓存区
        fw.close();     // 关闭io流
    }

    /**
     * 写入文件,按行写入数据
     * @param file 要写入的文档名
     * @param data  要写入的一条数据
     */
    public static void writeDataByLine(File file,String data) throws IOException {
        FileWriter fw;
        if(!file.exists()) {
            file.createNewFile();
        }
        if(file.exists()) {
            fw = new FileWriter(file,true);     //创建io流,写入文档
            @SuppressWarnings("resource")
            BufferedWriter bw = new BufferedWriter(fw); //创建缓存区,提高写入效率
            bw.write(data+"\n");	//写入数据
            bw.flush();     // 刷新缓存区
            bw.close();     // 关闭缓存区
            fw.close();     // 关闭io流
        }
    }
    /**
     * map 写入 本地
     * @param file 要写入的文档名
     * @param m 要写入的数据
     */
    public <K, V extends Comparable<? super V>> void writeDataByMap(File file, Map<K,V> m) throws IOException {
        Set<K> keys = m.keySet();
        List<String> l = new ArrayList<>();
        for(K key:keys) {
            String data= key +","+ m.get(key);
            l.add(data);
        }
        writeData(file, l);
    }

    private static final int BUFFER = 1024 * 8;

    /**
     * 压缩文件或目录
     *
     * @param fromPath 待压缩文件或路径
     * @param toPath   压缩文件,如 xx.zip
     */
    public static void compress(String fromPath, String toPath) throws IOException {
        File fromFile = new File(fromPath);
        File toFile = new File(toPath);
        if (!fromFile.exists()) {
            throw new FileNotFoundException(fromPath + "不存在!");
        }
        try (
                FileOutputStream outputStream = new FileOutputStream(toFile);
                CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
                ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)
        ) {
            String baseDir = "";
            compress(fromFile, zipOutputStream, baseDir);
        }
    }

    /**
     * 文件下载
     *
     * @param filePath 待下载文件路径
     * @param fileName 下载文件名称
     * @param delete   下载后是否删除源文件
     * @param response HttpServletResponse
     *                 建议请求方式: /a/b --> 接口 (c.xlsx要下载的文件,可以没有,也可以添加多个参数)
     *                 <a href="/a/b?fileName=c.xlsx">下载</a>
     *     接口:
     *     @RequestMapping("/a/b")
     *     public void getFile(HttpServletRequest request, HttpServletResponse response, String fileName) {
     *         try {
     *             FileUtil.download(path + File.separator + fileName, fileName, true, response);
     *         }catch (Exception e){
     *             e.printStackTrace();
     *         }
     * @throws Exception Exception
     */
    public static void download(String filePath, String fileName, Boolean delete, HttpServletResponse response) throws Exception {
        File file = new File(filePath);
        if (!file.exists())
            throw new Exception("文件未找到");
        String fileType = getFileType(file);
        if (!fileTypeIsValid(fileType)) {
            throw new Exception("暂不支持该类型文件下载");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } finally {
            if (delete)
                delete(filePath);
        }
    }

    /**
     * 递归删除文件或目录
     *
     * @param filePath 文件或目录
     */
    public static void delete(String filePath) {
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) Arrays.stream(files).forEach(f -> delete(f.getPath()));
        }
        file.delete();
    }

    /**
     * 获取文件类型
     *
     * @param file 文件
     * @return 文件类型
     * @throws Exception Exception
     */
    private static String getFileType(File file) throws Exception {
        Preconditions.checkNotNull(file);
        if (file.isDirectory()) {
            throw new Exception("file不是文件");
        }
        String fileName = file.getName();
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    /**
     * 校验文件类型是否是允许下载的类型
     * (出于安全考虑:https://github.com/wuyouzhuguli/FEBS-Shiro/issues/40)
     *      FebsConstant.VALID_FILE_TYPE = {"xlsx", "zip","docx","doc","txt"};
     * @param fileType fileType
     * @return Boolean
     */
    private static Boolean fileTypeIsValid(String fileType) {
        Preconditions.checkNotNull(fileType);
        fileType = StringUtils.lowerCase(fileType);
        return ArrayUtils.contains(FebsConstant.VALID_FILE_TYPE, fileType);
    }

    private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
        if (file.isDirectory()) {
            compressDirectory(file, zipOut, baseDir);
        } else {
            compressFile(file, zipOut, baseDir);
        }
    }

    private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {
        File[] files = dir.listFiles();
        if (files != null && ArrayUtils.isNotEmpty(files)) {
            for (File file : files) {
                compress(file, zipOut, baseDir + dir.getName() + "/");
            }
        }
    }

    private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
        if (!file.exists()) {
            return;
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zipOut.putNextEntry(entry);
            int count;
            byte[] data = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                zipOut.write(data, 0, count);
            }
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值