java導出txt文件 保存本地和瀏覽器直接下載兩種方式

第一種方式:保存到本地

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章