標籤:編碼 lis ali 位元組 注意 null lse color position
1. 匯出CSV檔案
/** * @Author lin.hongwen * @Date 2018/05/29 * 匯出CVS檔案到指定目錄 * * @param file csv檔案(路徑+檔案名稱),csv檔案不存在會自動建立 * @param dataList 資料 * @return */ public static boolean exportCsvFile(File file, List<String> dataList){ boolean isSucess=false; FileOutputStream out=null; OutputStreamWriter osw=null; BufferedWriter bw=null; try { out = new FileOutputStream(file); osw = new OutputStreamWriter(out); bw =new BufferedWriter(osw); if(dataList!=null && !dataList.isEmpty()){ for(String data : dataList){ bw.append(data).append("\r"); } } isSucess=true; } catch (Exception e) { 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; }
2.匯出從指定目錄下載檔案
OutputStream out = null; FileInputStream in = null; try { File file = new File(filePath+fileName); //把檔案名稱按UTF-8取出並按ISO8859-1編碼,保證快顯視窗中的檔案名稱中文不亂碼,中文不要太多,最多支援17個中文,因為header有150個位元組限制。 fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1"); //告訴瀏覽器輸出內容為流 response.setContentType("application/octet-stream"); //Content-Disposition中指定的類型是檔案的副檔名,並且彈出的下載對話方塊中的檔案類型圖片是按照檔案的副檔名顯示的,點儲存後,檔案以filename的值命名,檔案類型以Content中設定的為準。注意:在設定Content-Disposition頭欄位之前,一定要設定Content-Type頭欄位。 response.addHeader("Content-Disposition", "attachment;filename="+fileName); //設定內容長度 response.setHeader("Content-Length", String.valueOf(file.length())); out = response.getOutputStream(); in = new FileInputStream(file); byte[] b = new byte[1024]; int n; while((n=in.read(b))!=-1){ out.write(b, 0, n); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); in = null; } catch (IOException e) { e.printStackTrace(); } try { out.close(); out = null; } catch (IOException e) { e.printStackTrace(); } }
JAVA檔案操作