自定義TxT文件下載
阿新 • • 發佈:2018-11-18
第一次發部落格,如有不好,請大家多多指教
1,首先第一步:講資訊寫入到文字中
/** * 將資訊寫入txt文字 * @param datas 資訊內容 * @param fileName 資訊名稱 例如:資訊日誌.txt */ public void print(String datas,String fileName) { FileOutputStream fop = null; File file; try { //一個存放TXT臨時路徑 String savePath = "/data/web/file/uploads/contracts/"; File file1 = new File(savePath); //判讀路徑是否存在,如果不存在,就建立 if (!file1.exists()) { file1.mkdirs(); } file = new File(savePath+fileName); //判讀檔案是否存在,存在就刪除,不存在就建立 if(file.exists()) { file.delete();}else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile();} byte[] contentInBytes = datas.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2:將檔案下載
/** * 下載txt文字 * @param response * @param fileName 資訊名稱 例如:資訊日誌.txt * @throws Exception */ public void downloadFile(HttpServletResponse response,String fileName) throws Exception{ // File file = new File("D:\\1\\"+fileName); File file = new File("/data/web/file/uploads/contracts/"+fileName); InputStream inputStream = new FileInputStream(file);// 從系統磁碟檔案讀取資料 if(!file.exists()) { throw new IOException("檔案已不存在。"); } ServletUtils.setFileDownloadHeader(response, fileName); FileCopyUtils.copy(inputStream, response.getOutputStream()); response.getOutputStream().flush(); }
3.以上就是txt檔案下載的過程