从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;
}

猜你喜欢

转载自blog.csdn.net/qq_39141360/article/details/79564357