java导出txt文件 保存本地和浏览器直接下载两种方式

时间:2024-02-22 17:47:45

第一种方式:保存到本地

package com.cnki.tool.base;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class ExportTxtUtil {
    
    /**
     * 导出
     * 
     * @param file
     *            Txt文件(路径+文件名),Txt文件不存在会自动创建
     * @param dataList
     *            数据
     * @return
     */
    public static boolean exportTxt(File file, List<String> dataList) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            return exportTxtByOS(out, dataList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 导出
     * 
     * @param out
     *            输出流
     * @param dataList
     *            数据
     * @return
     */
    public static boolean exportTxtByOS(OutputStream out, List<String> dataList) {
        boolean isSucess = false;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            osw = new OutputStreamWriter(out);
            bw = new BufferedWriter(osw);
            // 循环数据
            for (int i = 0; i < dataList.size(); i++) {
                bw.append(dataList.get(i)).append("\r\n");
            }
            
            isSucess = true;
        } catch (Exception e) {
            e.printStackTrace();
            isSucess = false;
 
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                    bw = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                    osw = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return isSucess;
    }
 
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("Hello,World!");
        list.add("Hello,World!");
        list.add("Hello,World!");
        list.add("Hello,World!");
 
        String filePath = "D:/txt/";
        String fileName = java.util.UUID.randomUUID().toString().replaceAll("-", "")+".txt";
        File pathFile = new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdir();
        }
        String relFilePath = filePath + File.separator + fileName;
        File file = new File(relFilePath);
        if(!file.exists()){
            file.createNewFile();
        }
        boolean isSuccess=exportTxt(file,list);
        System.out.println(isSuccess);
        }
 
}

 


第二种方式浏览器直接下载:

    /* 拼接字符串
     * @author    
     * @param
     * @return
     */
    @RequestMapping("exportLog.do")
    public void exportLog(HttpServletResponse response){
        //获取日志
        List<DtmSystemLog> list = logService.getLogs();
        //拼接字符串
        StringBuffer text = new StringBuffer();
        for(DtmSystemLog log:list){
            text.append(log.getOpeuser());
            text.append("|");
            text.append(log.getOpedesc());
            text.append("|");
            text.append(dateString);
            text.append("\r\n");//换行字符
        }
        exportTxt(response,text.toString());
        
    }
 
 
    /* 导出txt文件
     * @author    
     * @param    response
     * @param    text 导出的字符串
     * @return
     */
    public void exportTxt(HttpServletResponse response,String text){
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition","attachment;filename="
                            + genAttachmentFileName( "文件名称", "JSON_FOR_UCC_")//设置名称格式,没有这个中文名称无法显示
                        + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                //LOGGER.error("关闭流对象出错 e:{}",e);
            }
        }
    }
 
//防止中文文件名显示出错    
 
public  String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }

 

远程调用浏览器下载txt文件方法:

import org.apache.commons.io.IOUtils;
 
    @RequestMapping({"/demp/common/downloadDeviceLog.do"})
    @ResponseBody
    public void downloadDeviceLog(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String logUrl = "https://**/2018-11-20.txt";
        try {
            String [] logUrlArray = logUrl.split("/");
            String fileName = logUrlArray[logUrlArray.length-1];
            URL url = new URL (logUrl);
            URLConnection uc = url.openConnection();
            response.setContentType("application/octet-stream");//设置文件类型
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(uc.getContentLength()));
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copy(uc.getInputStream(), out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }