-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSVUtil.java
70 lines (59 loc) · 1.75 KB
/
CSVUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package javaToolkit.lib.utils;
import java.io.FileWriter;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
public class CSVUtil {
public static void writeLine2Csv(List<String> strList, Path filePath) {
try {
FileWriter writer = new FileWriter(filePath.toString());
String collect = strList.stream().collect(Collectors.joining(","));
System.out.println(collect);
writer.write(collect);
writer.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void appendLine2Csv(List<String> strList, Path filePath) {
try {
String collect = strList.stream().collect(Collectors.joining(","));
// System.out.println(collect);
// pass true for appending
if (filePath.toFile().exists()) {
FileWriter writer = new FileWriter(filePath.toString(), true);
writer.write(collect);
writer.close();
} else {
FileWriter writer = new FileWriter(filePath.toString());
writer.write(collect);
writer.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void write2DArray2Csv(List<List<String>> strList, Path filePath) {
try {
FileWriter writer = null;
for (List<String> line : strList) {
String collect = line.stream().collect(Collectors.joining(","));
// System.out.println(collect);
// pass true for appending
if (filePath.toFile().exists()) {
writer = new FileWriter(filePath.toString(), true);
writer.write(collect.trim() + "\n");
} else {
writer = new FileWriter(filePath.toString());
writer.write(collect.trim() + "\n");
}
writer.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}