Java export txt file to save local and browser directly download two ways

The first way: save to local

package com.cnki.tool.base; 
 
import javax.servlet.http.HttpServletResponse;
 import java.io. * ;
 import java.util.ArrayList;
 import java.util.List; 
 
public  class ExportTxtUtil { 
    
    / ** 
     * Export 
     * 
     * @param file 
     * Txt file (path + file name), Txt file does not exist will be automatically created 
     * @param dataList 
     * data 
     * @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);
        }
 
}

 


The second way browser download directly:

    /* 拼接字符串
     * @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"); // line feed character 
        } 
        exportTxt (response, text.toString ()); 
        
    } 
 
 
    / * export txt file 
     * @author     
     * @param response 
     * @param text exported string 
     * @return 
     * / 
    public  void exportTxt (HttpServletResponse response, String text) { 
        response.setCharacterEncoding ( "utf-8" );
         // Set the response content type 
        response.setContentType ("text / plain " );
         // Set the file name and format
        response.addHeader ("Content-Disposition", "attachment; filename =" 
                            + genAttachmentFileName ("File name", "JSON_FOR_UCC_") // Set the name format, it cannot be displayed without this Chinese name 
                        + ".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 ("Error exporting file: {}", e); 
        } finally { try { 
                buff.close (); 
                outStr.close (); 
            } catch (Exception e) {
                 / / LOGGER.error ("Error of closing stream object e: {}", e);             } 
        } 
    } // Prevent Chinese file name display error     public   String genAttachmentFileName (String cnName, String defaultName) {
         try { 
            cnName = new String (cnName. getBytes ("gb2312"), "ISO8859-1" );

 

 
 
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }

 

Method of remotely calling browser to download txt file:

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();
        }
    }

 



Guess you like

Origin www.cnblogs.com/liuminchao/p/12695965.html