把字符串或者字符串list写入一个特定的文件

红太狼 2023-01-03 04:11 238阅读 0赞
  1. package com.centrin.process.utils;
  2. import java.io.*;
  3. import java.util.List;
  4. public class ExportFileUtils {
  5. public static void writeFile(String tmp, String filePath) throws IOException {
  6. BufferedWriter out = null;
  7. try {
  8. out = new BufferedWriter(new OutputStreamWriter(
  9. new FileOutputStream(new File(filePath), true)));
  10. out.write(tmp+"\r\n");
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. } finally {
  14. try {
  15. out.close();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. public static void writeFile(List<String> dataList, String filePath) throws IOException {
  22. //String filePath = "D:/opt/mapping/out/mytest04.csv";//设置文件的路径
  23. File sqlFile = new File(filePath); //创建备份文件对象
  24. FileOutputStream fos = null;//文件字节输出流
  25. OutputStreamWriter osw = null;//字节流转字符流
  26. BufferedWriter rw = null;//缓冲字符流
  27. try {
  28. fos = new FileOutputStream(sqlFile);
  29. osw = new OutputStreamWriter(fos);
  30. rw = new BufferedWriter(osw);
  31. for (String tmp : dataList) { //遍历所有备份sql
  32. rw.write(tmp);//向文件中写入sql
  33. rw.newLine();//文件换行
  34. rw.flush();//字符流刷新
  35. }
  36. } catch (FileNotFoundException e) {
  37. e.printStackTrace();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. } finally {
  41. //倒序依次关闭所有IO流
  42. if (rw != null) {
  43. try {
  44. rw.close();
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. if (osw != null) {
  50. try {
  51. osw.close();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. if (fos != null) {
  57. try {
  58. fos.close();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }
  64. }
  65. }

发表评论

表情:
评论列表 (有 0 条评论,238人围观)

还没有评论,来说两句吧...

相关阅读