11
11
*/
12
12
package com .zfoo .protocol .util ;
13
13
14
+ import com .zfoo .protocol .collection .ArrayUtils ;
15
+ import com .zfoo .protocol .collection .CollectionUtils ;
16
+
14
17
import java .util .ArrayList ;
15
18
import java .util .Collections ;
16
19
import java .util .HashMap ;
17
20
import java .util .List ;
21
+ import java .util .stream .Collectors ;
18
22
19
23
/**
20
24
* @author jaysunxiao
21
25
*/
22
26
public class CsvUtils {
23
27
24
- /**
25
- * CSV 字符串转对象列表
26
- *
27
- * @param csv CSV 格式字符串,第一行是表头
28
- * @param clazz 目标类
29
- * @param <T> 泛型类型
30
- * @return 对象列表
31
- */
32
- public static <T > List <T > parse (String csv , Class <T > clazz ) {
28
+
29
+ public static <T > List <T > toList (String csv , Class <T > clazz ) {
33
30
if (StringUtils .isEmpty (csv )) {
34
31
return Collections .emptyList ();
35
32
}
@@ -40,7 +37,7 @@ public static <T> List<T> parse(String csv, Class<T> clazz) {
40
37
}
41
38
42
39
var result = new ArrayList <T >();
43
- // 第一行作为表头
40
+ // first line as header
44
41
var headers = lines [0 ].split (StringUtils .COMMA_REGEX );
45
42
var headerIndex = new HashMap <String , Integer >();
46
43
for (var i = 0 ; i < headers .length ; i ++) {
@@ -49,7 +46,7 @@ public static <T> List<T> parse(String csv, Class<T> clazz) {
49
46
50
47
var fields = ReflectionUtils .notStaticAndTransientFields (clazz );
51
48
fields .forEach (it -> ReflectionUtils .makeAccessible (it ));
52
- // 从第二行开始解析
49
+ // next line from second line is data
53
50
for (var i = 1 ; i < lines .length ; i ++) {
54
51
var values = lines [i ].split (StringUtils .COMMA_REGEX );
55
52
@@ -70,4 +67,39 @@ public static <T> List<T> parse(String csv, Class<T> clazz) {
70
67
return result ;
71
68
}
72
69
70
+ public static <T > T [] toArray (String csv , Class <T > clazz ) {
71
+ return ArrayUtils .listToArray (toList (csv , clazz ), clazz );
72
+ }
73
+
74
+
75
+ public static <T > String toCsv (List <T > list ) {
76
+ if (CollectionUtils .isEmpty (list )) {
77
+ return StringUtils .EMPTY ;
78
+ }
79
+
80
+ var builder = new StringBuilder ();
81
+
82
+ // header
83
+ var clazz = list .get (0 ).getClass ();
84
+ var fields = ReflectionUtils .notStaticAndTransientFields (clazz );
85
+ fields .forEach (it -> ReflectionUtils .makeAccessible (it ));
86
+
87
+ var headers = fields .stream ().map (it -> it .getName ()).collect (Collectors .joining (StringUtils .COMMA_REGEX ));
88
+ builder .append (headers ).append (FileUtils .LS );
89
+
90
+ // data row
91
+ for (T obj : list ) {
92
+ var row = fields .stream ()
93
+ .map (it -> ReflectionUtils .getField (it , obj ))
94
+ .map (it -> it .toString ())
95
+ .collect (Collectors .joining (StringUtils .COMMA_REGEX ));
96
+ builder .append (row ).append (FileUtils .LS );
97
+ }
98
+
99
+ return builder .toString ();
100
+ }
101
+
102
+ public static <T > String toCsv (T [] array ) {
103
+ return toCsv (ArrayUtils .toList (array ));
104
+ }
73
105
}
0 commit comments