使用java将数据写入文件,并下载到客户端

2022-06-22 00:00:00 客户端 文件 写入

最近做了一个功能,觉得挺有意思,决定记录下来,以前也见过类似的功能,以为很高端,其实很简单。

第一步:写一个创建文件的工具类

public class CSVUtils{
	/**
     * CSV文件生成方法
     * @param head
     * @param dataList
     * @param outPutPath
     * @param filename
     * @return
     */
    public static File createCSVFile(List<Object> head, List<List<Object>> dataList,
                String outPutPath,String filename) {

        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv"); 
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // UTF-8使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    csvFile), "UTF-8"), 1024);
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     * @param row
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }
    
    
}

第二步:将数据按照格式写到文件,并且存放在服务器某个位置

public File createCSVFile(HttpServletRequest request,ObeEvent obeEventParam){
		PageHelper.startPage(obeEventParam.getPageNum(), obeEventParam.getPageSize());
		List<ObeEvent> eventList = obeEventMapper.selectByObeId(obeEventParam); 
		
         // 设置表格头
         Object[] head = {"设备编号", "事件时间", "事件类型", "事件详情"};
         List<Object> headList = Arrays.asList(head); 
         
         // 设置数据
         List<List<Object>> dataList = new ArrayList<List<Object>>();
         List<Object> rowList = null;
         for (int i = 0; i < eventList.size(); i++) {
             rowList = new ArrayList<Object>();
             ObeEvent obeEvent = eventList.get(i);
             rowList.add(obeEvent.getObeId());
             rowList.add("\t"+DateUtil.toDateTimeString(obeEvent.getObeTime())); 
             rowList.add(obeEvent.getEventType().replace("\"","\"\""));   
             
             String eventType = obeEvent.getEventType();
             String obeData = obeEvent.getObeData();
             JSONObject jsonObj = (JSONObject) JSONObject.parse(obeData);
             List<String> asList = Arrays.asList(eventType.substring(1, eventType.length()-1).
                       replaceAll("\"", "").split(","));
             JSONObject json = new JSONObject();
             for(String str : asList) {
            	 JSONObject obeEventDetail = jsonObj.getJSONObject(str.replaceAll("\"", "")); 
            	 json.put(str, obeEventDetail);
             } 
             
            
             rowList.add(json.toString().replaceAll("\"","\"\"")); 
             dataList.add(rowList);
         } 
         
         // 导出文件路径
         String downloadFilePath = "attachments2" + File.separator + "obeEvent" + 
                      File.separator + "download" + File.separator;
          
         // 导出文件名称
         String datetimeStr = DateUtil.toString(new Date(), "yyyyMMddHHmmss");
         String fileName = "事件列表_"+ obeEventParam.getObeId()+"_" + datetimeStr;
         
         // 导出CSV文件
         File csvFile = CSVUtils.createCSVFile(headList, dataList,downloadFilePath, fileName);
         
         return csvFile;//返回这个文件
     }

第三步:将返回的文件,以流的方式返回前端

public @ResponseBody Result<Object> exportObeEventDataExcel(HttpServletRequest request, 
         HttpServletResponse response,@RequestBody ObeEvent obeEvent){
     try {
			File csvFile = obeService.createCSVFile(request,obeEvent); 

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(csvFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header  
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(
                     csvFile.getName(), "UTF-8"));
            response.addHeader("Content-Length", "" + csvFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream"); 
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return Result.returnResult();  
        } catch (IOException e) { 
        	String message = "export ObeEvent Data Excel failed . ";
			LOGGER.error(message, e); 
			return Result.returnErrorResult(message);
        }
    }

为了方便大家看,有些地方换行了,大家注意下;
代码没什么难度,这里就不讲解了。

    原文作者:小糖豆巴拉巴拉
    原文地址: https://blog.csdn.net/qq_28483283/article/details/84143061
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章