java導出txt文件


1:vm模板頁面的代碼片段

                    <div class="col-sm-1">
                        <button type="button" class="btn btn-warning btn-sm" id="exportText"><i class="glyphicon glyphicon-file"/>導出文本文件</button>
                    </div>

2:JavaScript腳本文件的代碼片段

    /**
     * 導出文本文件
     */
    $("#exportText").on('click',function(){
        window.open(contextPath+'/exportText.json', '_blank');
    });

3:Java控制器的代碼片段

    /**
     * 導出文件文件
     * 用於UCC配置,將有效的數轉換成JSON字符串,然后導出文本文件
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportText.json")
    public void exportText(HttpServletResponse response){
        //獲取有效的數據
        List list = "i am godtrue 我最帥";//偽代碼
//將集合轉換成字符串 String jsonString = JSON.toJSONString(list); ExportTextUtil.writeToTxt(response,jsonString,"開關控制-JSON_FOR_UCC"); }

4:導出文本文件的工具類——此例的核心代碼,當然,這僅僅是一種方式,還有其他的各種的選擇

import java.io.BufferedOutputStream;
import java.text.MessageFormat;
import java.util.Calendar;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.jd.fce.ape.web.common.util.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 導出文件文件的工具類
 */
public class ExportTextUtil {
        /**
         * 聲明日志記錄器
         */
        private static final Logger LOGGER = LoggerFactory.getLogger(ExportTextUtil.class);

        /**
         * 導出文本文件
         * @param response
         * @param jsonString
         * @param fileName
         */
        public static void writeToTxt(HttpServletResponse response,String jsonString,String fileName) {//設置響應的字符集
            response.setCharacterEncoding("utf-8");
            //設置響應內容的類型
            response.setContentType("text/plain");
            //設置文件的名稱和格式
            response.addHeader(
                    "Content-Disposition",
                    "attachment; filename="
                            + FileUtil.genAttachmentFileName(fileName+ "_", "JSON_FOR_UCC_")
                            + MessageFormat.format("{0,date,yyyy-MM-dd HH:mm:ss}", new Object[]{Calendar.getInstance().getTime()})
                            + ".txt");//通過后綴可以下載不同的文件格式
            BufferedOutputStream buff = null;
            ServletOutputStream outStr = null;
            try {
                outStr = response.getOutputStream();
                buff = new BufferedOutputStream(outStr);
                buff.write(delNull(jsonString).getBytes("UTF-8"));
                buff.flush();
                buff.close();
            } catch (Exception e) {
                LOGGER.error("導出文件文件出錯,e:{}",e);
            } finally {try {
                    buff.close();
                    outStr.close();
                } catch (Exception e) {
                    LOGGER.error("關閉流對象出錯 e:{}",e);
                }
            }
        }

        /**
         * 如果字符串對象為 null,則返回空字符串,否則返回去掉字符串前后空格的字符串
         * @param str
         * @return
         */
        public static String delNull(String str) {
                String returnStr="";
                if (StringUtils.isNotBlank(str)) {
                    returnStr=str.trim();
                }
                return returnStr;
        }
}

5:解決導出文件名亂碼的工具類

public abstract class FileUtil {
    
    /**
     * 生成導出附件中文名。應對導出文件中文亂碼
     * <p>
     * response.addHeader("Content-Disposition", "attachment; filename=" + cnName);
     * 
     * @param cnName
     * @param defaultName
     * @return
     */
    public static String genAttachmentFileName(String cnName, String defaultName) {
        try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
            /*
            if (fileName.length() > 150) {
                fileName = new String( fileName.getBytes("gb2312"), "ISO8859-1" );
            }
            */
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }
}

 6:參看如下

http://qingfeng825.iteye.com/blog/461504


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM