本文共 3462 字,大约阅读时间需要 11 分钟。
随着项目上线,暂时处于闲置状态,所以趁闲带着团队对在这一年项目中做的比较好的组件,工具和实践总结和抽取出来,在我后续的随笔中将会陆续发布出来。今天主要是一个简单的maven小组件,对opencsv基于Annotation简单的封装,使得我们可以轻易的将CSV文件转化为List对像和把List对像导出为CSV文件。
项目托管地址于github 。
对于代码就不用多说了,简单看看如何使用。
Object
1 package opencsv.utils; 2 3 4 5 public class Person { 6 7 8 9 private int id;10 11 12 13 @Csv("person name")14 15 private String name;16 17 18 19 @Ignore20 21 private int age;22 23 24 25 public Person(int id, String name, int age) {26 27 this.id = id;28 29 this.name = name;30 31 this.age = age;32 33 }34 35 36 37 public Person() {38 39 40 41 }42 43 44 45 public int getId() {46 47 return id;48 49 }50 51 52 53 public void setId(int id) {54 55 this.id = id;56 57 }58 59 60 61 public String getName() {62 63 return name;64 65 }66 67 68 69 public void setName(String name) {70 71 this.name = name;72 73 }74 75 76 77 public int getAge() {78 79 return age;80 81 }82 83 84 85 public void setAge(int age) {86 87 this.age = age;88 89 }90 91 }92 93
Mapping会自动将没有ignore的字段作为CSV的映射属性名作为CSV列头,如果针对特殊列则可以标记@CSV解决。
1: 读取CSV:
(1) 基于Annotation映射方式
1 @Test 2 3 public void shouldGetPersonFromCSV() throws Exception { 4 5 StringReader reader = new StringReader("id,person name\n1,name1\n2,name2\n"); 6 7 ListpersonList = personCsvMapper 8 9 .withMapping("id", "id")10 11 .withMapping("person name", "name")12 13 .fromCsv(reader);14 15 16 17 assertThat(personList.size(), is(2));18 19 20 21 final Person first = personList.get(0);22 23 assertThat(first.getId(), is(1));24 25 assertThat(first.getName(), is("name1"));26 27 28 29 final Person second = personList.get(1);30 31 assertThat(second.getId(), is(2));32 33 assertThat(second.getName(), is("name2"));34 35 36 37 }38 39
(2) 自定义映射方式
1 @Test 2 3 public void shouldToCsv() throws Exception { 4 5 personCsvMapper.withMapping(new CsvColumnMapping(Person.class)); 6 7 final ArrayListlist = new ArrayList (); 8 9 list.add(new Person(1, "name1", 20));10 11 list.add(new Person(2, "name2", 30));12 13 final StringWriter writer = new StringWriter();14 15 16 17 personCsvMapper.toCsv(writer, list);18 19 20 21 final String text = writer.toString();22 23 assertThat(text, is("id,person name\n1,name1\n2,name2\n"));24 25 }
2: CSV输出
@Test public void shouldGetPersonFromCsv() throws Exception { StringReader reader = new StringReader("id,person name\n1,name1\n2,name2\n"); ListpersonList = new CsvMapper (Person.class) .withMapping(new CsvColumnMapping(Person.class)) .fromCsv(reader); assertThat(personList.size(), is(2)); final Person first = personList.get(0); assertThat(first.getId(), is(1)); assertThat(first.getName(), is("name1")); final Person second = personList.get(1); assertThat(second.getId(), is(2)); assertThat(second.getName(), is("name2")); }
最后在累赘下托管地址:。其他的相比不用再说了。