1. 程式人生 > >從Mysql查詢的結果,寫入txt檔案中,每個欄位用|分隔,下一條資料要換行

從Mysql查詢的結果,寫入txt檔案中,每個欄位用|分隔,下一條資料要換行

1.首先建立檔案
public static boolean createFile(String fileName, List<?> dtoList,
      Class<?> clazz, String path) {

   logger.debug("createFile start ");
   Boolean bool = false;
   String filenameTemp = path + fileName + NoahCodeConstant.TXT;// 檔案路徑+名稱+檔案型別
   File file = new File(filenameTemp);
   try 
{ // 如果檔案不存在,則建立新的檔案 if (!file.exists()) { file.createNewFile(); bool = true; System.out.println("建立檔案成功,the file is " + filenameTemp); // 建立檔案成功後,寫入內容到檔案裡 writeFileContent(filenameTemp, dtoList, clazz); } else { delFile(fileName,path); createFile
(fileName, dtoList, clazz,path); } } catch (Exception e) { logger.error("建立檔案失敗:",e); logger.error("建立檔案失敗,the file is " + filenameTemp); e.printStackTrace(); } logger.debug("createFile end "); return bool; }
2.向檔案中寫入內容
/**
 * 向檔案中寫入內容
 * @param filepath 檔案路徑與名稱
* @param dtoList 寫入的內容 * @param clazz * @return * @throws IOException */ public static boolean writeFileContent(String filepath, List<?> dtoList, Class<?> clazz) throws IOException { logger.debug("writeFileContent start "); Boolean bool = false; FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream fos = null; PrintWriter pw = null; try { File file = new File(filepath);// 檔案路徑(包括檔名稱) // 將檔案讀入輸入流 fis = new FileInputStream(file); isr = new InputStreamReader(fis); br = new BufferedReader(isr); fos = new FileOutputStream(file); pw = new PrintWriter(fos); Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < dtoList.size(); i++) { StringBuffer buffer = new StringBuffer(); for (int j = 0; j< fields.length;j++) { fields[j].setAccessible(true); buffer.append(fields[j].get(dtoList.get(i))); if (j != fields.length-1){ buffer.append(NoahCodeConstant.VERICAL_LINE); } } // 新寫入的行,換行 if (i != dtoList.size() - 1) { buffer.append(NoahCodeConstant.ENTED_KEY); } pw.write(buffer.toString()); } pw.flush(); bool = true; } catch (Exception e) { logger.error("寫入檔案失敗:",e); logger.error("寫入檔案失敗 " + filepath); e.printStackTrace(); } finally { // 不要忘記關閉 if (pw != null) { pw.close(); } if (fos != null) { fos.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } logger.debug("writeFileContent end "); return bool; }