獲取一個臨時檔案和對中文檔名字進行編碼的工具類
阿新 • • 發佈:2018-11-19
首先我們明白,一個檔案可以命名為任何名稱,比如一個excel,我們可以命名為不帶字尾,然後向裡面寫入對應的內容,只是在匯出的時候將檔案命名為正確的名字即可。
一個在當前使用者的預設臨時資料夾中生成一個當前日期的資料夾,然後再裡面寫入一個用UUID生成名字的檔案,常用於JavaEE中檔案下載的時候先生成一個臨時檔案,然後向此檔案中寫入資料之後開啟輸入流提供下載。
獲取一個臨時檔案,用於輸入內容後開啟inputstream提供下載
依賴Slf4j日誌和commons-io包
public static File getTmpFile() {// 獲取到當前系統的臨時工作目錄 String tempDirectoryPath = FileUtils.getTempDirectoryPath(); String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd"); String tmpFileDir = tempDirectoryPath + date; FileUtils.deleteQuietly(new File(tmpFileDir)); // 建立目錄(以日期格式命名) File file2 = newFile(tmpFileDir); file2.mkdir(); // 建立臨時檔案,UUID產生名稱 String fileName = UUIDUtil.getUUID2(); String tmpFileName = (tmpFileDir + "/" + fileName).replace("\\", "/"); File file = new File(tmpFileName); try { file.createNewFile(); }catch (IOException e) { log.error("getTmpFile error", e); } log.info("gene tempFile -> {}", file.getAbsolutePath()); return file; }
結果:
在檔案下載的時候對中文檔名進行編碼:
public String getFileName() { String name = "安全帽臺賬" + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls"; try { name = new String(name.getBytes("UTF-8"), "ISO8859-1"); } catch (UnsupportedEncodingException e) { log.error("getFileName error", e); return DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls"; } return name; }