java生成txt文档

代码如下:ps: "GBK"这样的编码格式可以替换更改比如"UTF-8","gbk","utf-8"...

 1 import org.apache.commons.lang.StringUtils;
 2 
 3 import java.io.*;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 public class TestMain1 {
 8     public static void main(String[] args) {
 9         List<String> stringList = new ArrayList<>();
10         stringList.add("1哈哈 黑");
11         stringList.add("2嘿嘿 黑");
12         writeDataHubData(stringList, "111");
13         System.out.println(111);
14     }
15 
16     /**
17      * 写入txt文件
18      *
19      * @param result
20      * @param fileName
21      * @return
22      */
23     public static boolean writeDataHubData(List<String> result, String fileName) {
24         long start = System.currentTimeMillis();
25         String filePath = "D:\\temp\\txt";
26         StringBuilder content = new StringBuilder();
27         boolean flag = false;
28         BufferedWriter out = null;
29         try {
30             if (result != null && !result.isEmpty() && StringUtils.isNotEmpty(fileName)) {
31                 fileName += "_" + System.currentTimeMillis() + ".txt";
32                 File pathFile = new File(filePath);
33                 if (!pathFile.exists()) {
34                     pathFile.mkdirs();
35                 }
36                 String relFilePath = filePath + File.separator + fileName;
37                 File file = new File(relFilePath);
38                 if (!file.exists()) {
39                     file.createNewFile();
40                 }
41                 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
42 //                //标题头
43 //                out.write("curr_time,link_id,travel_time,speed,reliabilitycode,link_len,adcode,time_stamp,state,public_rec_time,ds");
44 //                out.newLine();
45                 for (String info : result) {
46 
47                     out.write(info);
48                     out.newLine();
49                 }
50                 flag = true;
51 //                logger.info("写入文件耗时:*********************************" + (System.currentTimeMillis() - start) + "毫秒");
52                 System.out.println("写入文件耗时:*********************************" + (System.currentTimeMillis() - start) + "毫秒");
53             }
54         } catch (IOException e) {
55             e.printStackTrace();
56         } finally {
57             if (out != null) {
58                 try {
59                     out.flush();
60                     out.close();
61                 } catch (IOException e) {
62                     e.printStackTrace();
63                 }
64             }
65             return flag;
66         }
67     }
68 }

参考链接:

https://blog.csdn.net/fenfenguai/article/details/78920711

猜你喜欢

转载自www.cnblogs.com/m-yb/p/11528022.html
今日推荐