# super-csv **Repository Path**: outllok/super-csv ## Basic Information - **Project Name**: super-csv - **Description**: 使用super-csv官方提供的例子-简化版 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-05-08 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # super-csv #### 介绍 使用super-csv官方提供的例子-简化版 1. github下载地址 https://github.com/super-csv/super-csv 需要的jar super-csv-2.4.0.jar 2. 写入 方式一 使用CsvBeanWriter ``` import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.FmtDate; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; public class Write { //第一步 定义单元格约束 若出错,会生成一张只有表头而没有内容的csv文件 private static CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) 唯一值 new NotNull(), // firstName //不允许为空null 但可以是 "" new NotNull(), // lastName new FmtDate("dd/MM/yyyy"), // birthDate 日期的格式 new NotNull(), // mailingAddress new Optional(new FmtBool("Y", "N")), //married 可为空 true->Y false->N new Optional(), // numberOfKids new NotNull(), // favouriteQuote new NotNull(), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } //第二步 写入内容到csv文件中 特殊字符使用\转义 \n换行 private static void writeWithCsvBeanWriter() throws Exception { // 创建自定义的实体类 final CustomerBean john = new CustomerBean( "1", "John", "Dunbar", new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); final CustomerBean bob = new CustomerBean( "2", "Bob", "Down", new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); final List customers = Arrays.asList(john, bob); ICsvBeanWriter beanWriter = null; try { beanWriter = new CsvBeanWriter(new FileWriter("/writeWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); // 定义表头元素的值 final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; final CellProcessor[] processors = getProcessors(); //写入表头 beanWriter.writeHeader(header); // 写入数据 for(final CustomerBean customer : customers ) { beanWriter.write(customer, header, processors); } } finally { if( beanWriter != null ) { beanWriter.close(); } } } public static void main(String[] args) throws Exception{ writeWithCsvBeanWriter(); } } public class CustomerBean { private String customerNo; private String firstName; private String lastName; private Date birthDate; private String mailingAddress; private Boolean married; private Integer numberOfKids; private String favouriteQuote; private String email; private Long loyaltyPoints; //….省略get/set 构造方法 } ``` 方式二 使用 CsvListWriter 不推荐 除非没有其它的实现方式 ``` import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.FmtDate; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.CsvListWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.io.ICsvListWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; public class CsvListWriterTest { //第一步 定义单元格约束 若出错,会生成一张只有表头而没有内容的csv文件 private static CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) 唯一值 new NotNull(), // firstName //不允许为空null 但可以是 "" new NotNull(), // lastName new FmtDate("dd/MM/yyyy"), // birthDate 日期的格式 new NotNull(), // mailingAddress new Optional(new FmtBool("Y", "N")), //married 可为空 true->Y false->N new Optional(), // numberOfKids new NotNull(), // favouriteQuote new NotNull(), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } //第二步 写入内容到csv文件中 特殊字符使用\转义 \n换行 private static void writeWithCsvListWriter() throws Exception { // create the customer Lists (CsvListWriter also accepts arrays!) final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar", new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L }); final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L }); ICsvListWriter listWriter = null; try { listWriter = new CsvListWriter(new FileWriter("/writeWithCsvListWriter.csv"), CsvPreference.STANDARD_PREFERENCE); final CellProcessor[] processors = getProcessors(); final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; // write the header listWriter.writeHeader(header); // write the customer lists listWriter.write(john, processors); listWriter.write(bob, processors); } finally { if( listWriter != null ) { listWriter.close(); } } } public static void main(String[] args) throws Exception{ writeWithCsvListWriter(); } } ``` 方式3 使用CsvMapWriter 如果不能使用csvbeanwriter,csvmapwriter是一个很好的折衷方案 ``` import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.FmtDate; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.CsvMapWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.io.ICsvMapWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.*; public class CsvMapWriterTest { //第一步 定义单元格约束 若出错,会生成一张只有表头而没有内容的csv文件 private static CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) 唯一值 new NotNull(), // firstName //不允许为空null 但可以是 "" new NotNull(), // lastName new FmtDate("dd/MM/yyyy"), // birthDate 日期的格式 new NotNull(), // mailingAddress new Optional(new FmtBool("Y", "N")), //married 可为空 true->Y false->N new Optional(), // numberOfKids new NotNull(), // favouriteQuote new NotNull(), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } //第二步 写入内容到csv文件中 特殊字符使用\转义 \n换行 private static void writeWithCsvMapWriter() throws Exception { final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; // create the customer Maps (using the header elements for the column keys) final Map john = new HashMap(); john.put(header[0], "1"); john.put(header[1], "John"); john.put(header[2], "Dunbar"); john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime()); john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States"); john.put(header[5], null); john.put(header[6], null); john.put(header[7], "\"May the Force be with you.\" - Star Wars"); john.put(header[8], "jdunbar@gmail.com"); john.put(header[9], 0L); final Map bob = new HashMap(); bob.put(header[0], "2"); bob.put(header[1], "Bob"); bob.put(header[2], "Down"); bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime()); bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States"); bob.put(header[5], true); bob.put(header[6], 0); bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind"); bob.put(header[8], "bobdown@hotmail.com"); bob.put(header[9], 123456L); ICsvMapWriter mapWriter = null; try { mapWriter = new CsvMapWriter(new FileWriter("/writeWithCsvMapWriter.csv"), CsvPreference.STANDARD_PREFERENCE); final CellProcessor[] processors = getProcessors(); // write the header mapWriter.writeHeader(header); // write the customer maps mapWriter.write(john, header, processors); mapWriter.write(bob, header, processors); } finally { if( mapWriter != null ) { mapWriter.close(); } } } public static void main(String[] args) throws Exception{ writeWithCsvMapWriter(); } } ``` 3.读取 方式一  CsvBeanReader ``` import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseBool; import org.supercsv.cellprocessor.ParseDate; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.StrRegEx; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanReader; import org.supercsv.io.ICsvBeanReader; import org.supercsv.prefs.CsvPreference; import java.io.FileReader; public class TestCsvBeanReader { private static CellProcessor[] getProcessors() { final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! StrRegEx.registerMessage(emailRegex, "must be a valid email address"); final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) new NotNull(), // firstName new NotNull(), // lastName new ParseDate("dd/MM/yyyy"), // birthDate new NotNull(), // mailingAddress new Optional(new ParseBool()), // married new Optional(new ParseInt()), // numberOfKids new NotNull(), // favouriteQuote new StrRegEx(emailRegex), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } private static void readWithCsvBeanReader() throws Exception { ICsvBeanReader beanReader = null; try { beanReader = new CsvBeanReader(new FileReader("/readWithCsvBeanReader.csv"), CsvPreference.STANDARD_PREFERENCE); // the header elements are used to map the values to the bean (names must match) final String[] header = beanReader.getHeader(true); final CellProcessor[] processors = getProcessors(); CustomerBean customer; while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { System.out.println(String.format( "lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), beanReader.getRowNumber(), customer)); } } finally { if( beanReader != null ) { beanReader.close(); } } } public static void main(String[] args) throws Exception{ readWithCsvBeanReader(); } } ``` lineNo=4, rowNo=2, customer=CustomerBean{customerNo='1', firstName='John', lastName='Dunbar', birthDate=Wed Jun 13 00:00:00 CST 1945, mailingAddress='1600 Amphitheatre Parkway Mountain View, CA 94043 United States', married=null, numberOfKids=null, favouriteQuote='"May the Force be with you." - Star Wars', email='jdunbar@gmail.com', loyaltyPoints=0} lineNo=7, rowNo=3, customer=CustomerBean{customerNo='2', firstName='Bob', lastName='Down', birthDate=Tue Feb 25 00:00:00 CST 1919, mailingAddress='1601 Willow Rd. Menlo Park, CA 94025 United States', married=true, numberOfKids=0, favouriteQuote='"Frankly, my dear, I don't give a damn." - Gone With The Wind', email='bobdown@hotmail.com', loyaltyPoints=123456} 方式二  CsvListReader ``` import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseBool; import org.supercsv.cellprocessor.ParseDate; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.StrRegEx; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvListReader; import org.supercsv.io.ICsvListReader; import org.supercsv.prefs.CsvPreference; import java.io.FileReader; import java.util.List; public class TestCsvListReader { private static CellProcessor[] getProcessors() { final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! StrRegEx.registerMessage(emailRegex, "must be a valid email address"); final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) new NotNull(), // firstName new NotNull(), // lastName new ParseDate("dd/MM/yyyy"), // birthDate new NotNull(), // mailingAddress new Optional(new ParseBool()), // married new Optional(new ParseInt()), // numberOfKids new NotNull(), // favouriteQuote new StrRegEx(emailRegex), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } private static void readWithCsvListReader() throws Exception { ICsvListReader listReader = null; try { listReader = new CsvListReader(new FileReader("/writeWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); listReader.getHeader(true); // skip the header (can't be used with CsvListReader) final CellProcessor[] processors = getProcessors(); List customerList; while( (customerList = listReader.read(processors)) != null ) { System.out.println(String.format("lineNo=%s, rowNo=%s, customerList=%s", listReader.getLineNumber(), listReader.getRowNumber(), customerList)); } } finally { if( listReader != null ) { listReader.close(); } } } public static void main(String[] args) throws Exception{ readWithCsvListReader(); } } lineNo=4, rowNo=2, customerList=[1, John, Dunbar, Wed Jun 13 00:00:00 CST 1945, 1600 Amphitheatre Parkway Mountain View, CA 94043 United States, null, null, "May the Force be with you." - Star Wars, jdunbar@gmail.com, 0] lineNo=7, rowNo=3, customerList=[2, Bob, Down, Tue Feb 25 00:00:00 CST 1919, 1601 Willow Rd. Menlo Park, CA 94025 United States, true, 0, "Frankly, my dear, I don't give a damn." - Gone With The Wind, bobdown@hotmail.com, 123456] 方式三  CsvMapReader import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseBool; import org.supercsv.cellprocessor.ParseDate; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.StrRegEx; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanReader; import org.supercsv.io.CsvMapReader; import org.supercsv.io.ICsvBeanReader; import org.supercsv.io.ICsvMapReader; import org.supercsv.prefs.CsvPreference; import java.io.FileReader; import java.util.Map; public class TestCsvMapReader { private static CellProcessor[] getProcessors() { final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! StrRegEx.registerMessage(emailRegex, "must be a valid email address"); final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) new NotNull(), // firstName new NotNull(), // lastName new ParseDate("dd/MM/yyyy"), // birthDate new NotNull(), // mailingAddress new Optional(new ParseBool()), // married new Optional(new ParseInt()), // numberOfKids new NotNull(), // favouriteQuote new StrRegEx(emailRegex), // email new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints }; return processors; } private static void readWithCsvMapReader() throws Exception { ICsvMapReader mapReader = null; try { mapReader = new CsvMapReader(new FileReader("/writeWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); // the header columns are used as the keys to the Map final String[] header = mapReader.getHeader(true); final CellProcessor[] processors = getProcessors(); Map customerMap; while( (customerMap = mapReader.read(header, processors)) != null ) { System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), mapReader.getRowNumber(), customerMap)); } } finally { if( mapReader != null ) { mapReader.close(); } } } public static void main(String[] args) throws Exception{ readWithCsvMapReader(); } } lineNo=4, rowNo=2, customerMap={firstName=John, lastName=Dunbar, numberOfKids=null, mailingAddress=1600 Amphitheatre Parkway Mountain View, CA 94043 United States, birthDate=Wed Jun 13 00:00:00 CST 1945, married=null, loyaltyPoints=0, customerNo=1, favouriteQuote="May the Force be with you." - Star Wars, email=jdunbar@gmail.com} lineNo=7, rowNo=3, customerMap={firstName=Bob, lastName=Down, numberOfKids=0, mailingAddress=1601 Willow Rd. Menlo Park, CA 94025 United States, birthDate=Tue Feb 25 00:00:00 CST 1919, married=true, loyaltyPoints=123456, customerNo=2, favouriteQuote="Frankly, my dear, I don't give a damn." - Gone With The Wind, email=bobdown@hotmail.com} 4.部分属性值的写入 方式一 using CsvBeanWriter import org.supercsv.cellprocessor.ConvertNullTo; import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.FmtDate; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; public class partialWriteWithCsvBeanWriterTest { private static void partialWriteWithCsvBeanWriter() throws Exception { // create the customer beans final CustomerBean john = new CustomerBean( "1", "John", "Dunbar", new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); final CustomerBean bob = new CustomerBean( "2", "Bob", "Down", new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); final List customers = Arrays.asList(john, bob); ICsvBeanWriter beanWriter = null; try { beanWriter = new CsvBeanWriter(new FileWriter("/partialWriteWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); // only map 5 of the 10 fields final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; // assign a default value for married (if null), and write numberOfKids as an empty column if null final CellProcessor[] processors = new CellProcessor[] { //customerNo new UniqueHashCode(), //firstName new NotNull(), //lastName new NotNull(), //married 若为空显示no response;若为true显示yes,false显示no new ConvertNullTo("no response", new FmtBool("yes", "no")), //numberOfKids new Optional() }; // write the header beanWriter.writeHeader(header); // write the customer beans for( final CustomerBean customer : customers ) { beanWriter.write(customer, header, processors); } } finally { if( beanWriter != null ) { beanWriter.close(); } } } public static void main(String[] args) throws Exception{ partialWriteWithCsvBeanWriter(); } } 方式二 Partial writing with CsvListWriter import org.supercsv.cellprocessor.ConvertNullTo; import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.CsvListWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.io.ICsvListWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.Arrays; import java.util.List; public class partialWriteWithCsvListWriterTest { private static void partialWriteWithCsvListWriter() throws Exception { final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; // create the customer Lists (CsvListWriter also accepts arrays!) final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null}); final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 }); ICsvListWriter listWriter = null; try { listWriter = new CsvListWriter(new FileWriter("/partialWriteWithCsvListWriter.csv"), CsvPreference.STANDARD_PREFERENCE); // assign a default value for married (if null), and write numberOfKids as an empty column if null final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; // write the header listWriter.writeHeader(header); // write the customer Lists listWriter.write(john, processors); listWriter.write(bob, processors); } finally { if( listWriter != null ) { listWriter.close(); } } } public static void main(String[] args) throws Exception{ partialWriteWithCsvListWriter(); } } 方式三 Partial writing with CsvMapWriter import org.supercsv.cellprocessor.ConvertNullTo; import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.CsvMapWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.io.ICsvMapWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileWriter; import java.util.*; public class partialWriteWithCsvMapWriterTest { private static void partialWriteWithCsvMapWriter() throws Exception { final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; // create the customer Maps (using the header elements for the column keys) final Map john = new HashMap(); john.put(header[0], "1"); john.put(header[1], "John"); john.put(header[2], "Dunbar"); john.put(header[3], null); john.put(header[4], null); final Map bob = new HashMap(); bob.put(header[0], "2"); bob.put(header[1], "Bob"); bob.put(header[2], "Down"); bob.put(header[3], true); bob.put(header[4], 0); ICsvMapWriter mapWriter = null; try { mapWriter = new CsvMapWriter(new FileWriter("/partialWriteWithCsvMapWriter.csv"), CsvPreference.STANDARD_PREFERENCE); // assign a default value for married (if null), and write numberOfKids as an empty column if null final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null }; // write the header mapWriter.writeHeader(header); // write the customer Maps mapWriter.write(john, header, processors); mapWriter.write(bob, header, processors); } finally { if( mapWriter != null ) { mapWriter.close(); } } } public static void main(String[] args) throws Exception{ partialWriteWithCsvMapWriter(); } } 5.读取csv文件,部分列的值 方式一 Partial reading with CsvBeanReader import org.supercsv.cellprocessor.ConvertNullTo; import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanReader; import org.supercsv.io.CsvListWriter; import org.supercsv.io.ICsvBeanReader; import org.supercsv.io.ICsvListWriter; import org.supercsv.prefs.CsvPreference; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; import java.util.List; public class partialReadWithCsvBeanReaderTest { private static void partialReadWithCsvBeanReader() throws Exception { ICsvBeanReader beanReader = null; try { beanReader = new CsvBeanReader(new FileReader("/partialWriteWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); beanReader.getHeader(true); // skip past the header (we're defining our own) // only map the first 3 columns - setting header elements to null means those columns are ignored final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null}; // no processing required for ignored columns final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), new NotNull(), null, null}; CustomerBean customer; while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), beanReader.getRowNumber(), customer)); } } finally { if( beanReader != null ) { beanReader.close(); } } } public static void main(String[] args) throws Exception{ partialReadWithCsvBeanReader(); } } ``` lineNo=2, rowNo=2, customer=CustomerBean{customerNo='1', firstName='John', lastName='Dunbar', birthDate=null, mailingAddress='null', married=null, numberOfKids=null, favouriteQuote='null', email='null', loyaltyPoints=null} lineNo=3, rowNo=3, customer=CustomerBean{customerNo='2', firstName='Bob', lastName='Down', birthDate=null, mailingAddress='null', married=null, numberOfKids=null, favouriteQuote='null', email='null', loyaltyPoints=null} 方式二 Partial reading with CsvMapReader 读取的特点,若为空的字段值不显示 ``` import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.LMinMax; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.UniqueHashCode; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanReader; import org.supercsv.io.CsvMapReader; import org.supercsv.io.ICsvBeanReader; import org.supercsv.io.ICsvMapReader; import org.supercsv.prefs.CsvPreference; import java.io.FileReader; import java.util.Map; public class partialReadWithCsvMapReaderTest { private static void partialReadWithCsvMapReader() throws Exception { ICsvMapReader mapReader = null; try { mapReader = new CsvMapReader(new FileReader("/partialWriteWithCsvBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE); mapReader.getHeader(true); // skip past the header (we're defining our own) // only map the first 3 columns - setting header elements to null means those columns are ignored final String[] header = new String[] { "customerNo", "firstName", "lastName", null, "numberOfKids" }; // apply some constraints to ignored columns (just because we can) final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), new NotNull(), new Optional(), //读取该字段的值的范围,超出报错 new LMinMax(0L, LMinMax.MAX_LONG) }; Map customerMap; while( (customerMap = mapReader.read(header, processors)) != null ) { System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), mapReader.getRowNumber(), customerMap)); } } finally { if( mapReader != null ) { mapReader.close(); } } } public static void main(String[] args) throws Exception{ partialReadWithCsvMapReader(); }} lineNo=2, rowNo=2, customerMap={firstName=John, lastName=Dunbar, numberOfKids=34, customerNo=1} lineNo=3, rowNo=3, customerMap={firstName=Bob, lastName=Down, numberOfKids=0, customerNo=2} ```