java 查询数据之后将对象集合保存为txt/csv文件,以流的方式返回前端

 将查询到的对象集合转为json  使用的为JSONArray.fromObject()方法 需要引入依赖为json-lib包  对比fastjson,它会将空值也获取到,fastjson不会取空值

<!--json -->
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.2</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.10</version>
    </dependency>
  </dependencies>
/**
     * 生成 txt文件
     *
     * @author yulisao
     * @date 2018年9月4日 下午2:32:26
     *
     * @param dataList 数据列表
     * @param outPath  写入路径
     * @param fileName 文件名称
     * @return
     */
    public String exportTxtFile(List<?> dataList, String outPath, String fileName) {
        makeDir(outPath);
        FileWriter fw = null;
        String path = outPath + File.separator + fileName + ".txt";
        File file = new File(path);
        long start = System.currentTimeMillis();
        try {
            System.out.println("txt文件创建开始");
            if (file.exists()) {
                System.out.println("已存在文件");
            }
            fw = new FileWriter(file);
            JSONArray jsa = JSONArray.fromObject(dataList);
            String result = jsa.toString();
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.flush();
            bw.close();
            long length = file.length();
            long end = System.currentTimeMillis();
            System.out.println("txt文件创建成功,用时" + (end - start) + "ms,文件大小 " + length + " byte,文件输出路径:" + path);
            return path;
        } catch (IOException e) {
            System.out.println("txt文件创建失败");
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }
    /**
     * 创建文件目录
     *
     * @param outPath
     * @return void
     *
     * @author yulisao
     * @date 2018年9月4日 下午2:34:45
     */
    public void makeDir(String outPath){
        File file = new File(outPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

生成csv文件使用 EasyExcel

@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
    @ExcelProperty("字符串标题")
    private String string;
    @ExcelProperty("日期标题")
    private Date date;
    @ExcelProperty("数字标题")
    private Double doubleData;
    /**
     * 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;
}
   /**
     * 最简单的写
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link DemoData}
     * <p>
     * 2. 直接写即可
     */
    @Test
    public void simpleWrite() {
        // 注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照 重复多次写入

        // 写法1 JDK8+
        // since: 3.0.0-beta1
        String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class)
            .sheet("模板")
            .doWrite(() -> {
                // 分页查询数据
                return data();
            });

        // 写法2
        fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

        // 写法3
        fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(data(), writeSheet);
        }
    }

其他方式请参考EasyExcel官方文档

返回流给前端

package com.originspace.env.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * <p>
 * 文件工具类
 * </p>
 *
 */
@Slf4j
@Component
public class FileUtil {

    //输入处理流
    InputStream inputStream = null;
    //输出处理流
    OutputStream outputStream = null;

    /**
     * 文件下载
     * @param filePath 文件在服务器的全路径
     * @param response response
     */
    public void fileDownload(String filePath, HttpServletResponse response){
        long start = System.currentTimeMillis();

        File file = new File(filePath);
        //文件名,不含后缀
        String fileSimpleName = filePath.substring(filePath.lastIndexOf("/")+1);

        if (!file.exists()){//如果文件不存在
            log.error("下载的文件不存在");
            return;
        }

        try {
            //定义处理流
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = new BufferedOutputStream(response.getOutputStream());

            log.debug("设置response携带信息");
            log.debug("文件的大小:"+file.length());
            response.reset();
            // 设置在下载框默认显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileSimpleName, "UTF-8"));
            //写明文件大小
            response.addHeader("Content-Length", "" + file.length());
            // 指明response的返回对象是文件流
            response.setContentType("application/octet-stream");
            //response.setContentType("multipart/form-data");


            log.debug("开始读取文件流");
            //返回从该输入流中可以读取(或跳过)的字节数的估计值,而不会被下一次调用此输入流的方法阻塞
            byte[] bytes = new byte[inputStream.available()];
            //将pdf的内容写入bytes中
            inputStream.read(bytes);
            //将bytes中的内容写入
            outputStream.write(bytes);
            //刷新输出流,否则不会写出数据
            outputStream.flush();

            log.debug("======文件下载处理完成==========");

        } catch (FileNotFoundException e) {
            log.error("转换的pad文件未找到"+e.getMessage());
            return;
        } catch (IOException e) {
            log.error("文件读写异常"+e.getMessage());
            return;
        }finally {//关闭输入流、输出流
            try {
                if (inputStream != null){
                    inputStream.close();
                    log.debug("输入流关闭成功!");

                }
                if (outputStream != null){
                    outputStream.close();
                    log.debug("输出流关闭成功!");
                }

                long end = System.currentTimeMillis();
                log.debug("文件流处理时间"+(end-start));

            } catch (IOException e) {
                 log.error("关闭处理流出现异常"+e.getMessage());
                 return;
            }
        }

    }

    /**
     * 删除文件
     * @param path 需要删除文件的全路径
     * @return 是否删除成功
     */
    public boolean fileDelete(String path){
        File file = new File(path);
        if (file.exists()){
            file.delete();
            return true;
        }else {
            return false;
        }

    }

    /**
     * 删除目录,及目录下的文件
     * @param directory 目录全路径
     */
    public void fileDirDelete(String directory){
        File dir = new File(directory);

        if (!dir.exists()){//如果该目录不存在,则直接退出方法
            log.debug("该路径不存在:"+dir.getPath());
            return;
        }

        File[] files = dir.listFiles();

        for (File file : files) {
            if (file.isDirectory()){
                log.debug("进入目录:"+file.getPath());
                fileDirDelete(file.getPath());
            }else {
                log.debug("删除文件:"+file.getPath());
                file.delete();
            }
        }

        dir.delete();
        log.debug(dir.getPath()+"目录已经删除");
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值