add methods

This commit is contained in:
Looly 2021-06-24 08:26:46 +08:00
parent d6fd4e259b
commit 2c30de4fae
3 changed files with 18 additions and 35 deletions

View File

@ -7,6 +7,7 @@
### 🐣新特性
* 【core 】 增加Convert.toSet方法issue#I3XFG2@Gitee
* 【core 】 CsvWriter增加writeBeans方法pr#345@Gitee
### 🐞Bug修复
* 【json 】 修复XML转义字符的问题issue#I3XH09@Gitee

View File

@ -19,10 +19,8 @@ import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
/**
* CSV数据写出器
@ -217,13 +215,17 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
*/
public CsvWriter writeBeans(Collection<?> beans) {
if (CollUtil.isNotEmpty(beans)) {
List<Collection<Object>> res = new ArrayList<>();
boolean isFirst = true;
Map<String, Object> map;
for (Object bean : beans) {
res.add(BeanUtil.beanToMap(bean).keySet().stream().map(k -> (Object) k).collect(Collectors.toList()));
break;
map = BeanUtil.beanToMap(bean);
if(isFirst){
writeLine(map.keySet().toArray(new String[0]));
isFirst = false;
}
writeLine(Convert.toStrArray(map.values()));
}
res.addAll(beans.stream().map(bean -> BeanUtil.beanToMap(bean).values()).collect(Collectors.toList()));
write(res);
flush();
}
return this;
}

View File

@ -3,6 +3,7 @@ package cn.hutool.core.text.csv;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import lombok.Data;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@ -64,49 +65,27 @@ public class CsvUtilTest {
@Test
@Ignore
public void writeBeansTest() {
@Data
class Student {
Integer id;
String name;
Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
CsvWriter writer = CsvUtil.getWriter("d:/test/testWriteBeans.csv", CharsetUtil.CHARSET_UTF_8);
List<Student> students = new ArrayList<>();
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
student1.setId(1);
student1.setName("张三");
student1.setAge(18);
Student student2 = new Student();
student2.setId(2);
student2.setName("李四");
student2.setAge(22);
Student student3 = new Student();
student3.setId(3);
student3.setName("王五");
student3.setAge(31);
@ -115,6 +94,7 @@ public class CsvUtilTest {
students.add(student2);
students.add(student3);
writer.writeBeans(students);
writer.close();
}
@Test