View Javadoc
1   /*
2    * Copyright 2007 Kasper B. Graversen
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.supercsv.example;
17  
18  import java.io.FileWriter;
19  import java.sql.ResultSet;
20  import java.util.Arrays;
21  import java.util.Calendar;
22  import java.util.GregorianCalendar;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.supercsv.cellprocessor.ConvertNullTo;
28  import org.supercsv.cellprocessor.FmtBool;
29  import org.supercsv.cellprocessor.FmtDate;
30  import org.supercsv.cellprocessor.Optional;
31  import org.supercsv.cellprocessor.constraint.LMinMax;
32  import org.supercsv.cellprocessor.constraint.NotNull;
33  import org.supercsv.cellprocessor.constraint.UniqueHashCode;
34  import org.supercsv.cellprocessor.ift.CellProcessor;
35  import org.supercsv.io.CsvBeanWriter;
36  import org.supercsv.io.CsvListWriter;
37  import org.supercsv.io.CsvMapWriter;
38  import org.supercsv.io.CsvResultSetWriter;
39  import org.supercsv.io.ICsvBeanWriter;
40  import org.supercsv.io.ICsvListWriter;
41  import org.supercsv.io.ICsvMapWriter;
42  import org.supercsv.io.ICsvResultSetWriter;
43  import org.supercsv.mock.CustomerBean;
44  import org.supercsv.mock.ResultSetMock;
45  import org.supercsv.prefs.CsvPreference;
46  
47  /**
48   * Examples of writing CSV files.
49   */
50  public class Writing {
51  	
52  	public static void main(String[] args) throws Exception {
53  		writeWithCsvBeanWriter();
54  		writeWithResultSetWriter();
55  		writeWithCsvListWriter();
56  		writeWithCsvMapWriter();
57  		partialWriteWithCsvBeanWriter();
58  		partialWriteWithCsvListWriter();
59  		partialWriteWithCsvMapWriter();
60  	}
61  	
62  	/**
63  	 * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. All values
64  	 * are converted to Strings before writing (there's no need to convert them), and null values will be written as
65  	 * empty columns (no need to convert them to "").
66  	 * 
67  	 * @return the cell processors
68  	 */
69  	private static CellProcessor[] getProcessors() {
70  		
71  		final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique)
72  			new NotNull(), // firstName
73  			new NotNull(), // lastName
74  			new FmtDate("dd/MM/yyyy"), // birthDate
75  			new NotNull(), // mailingAddress
76  			new Optional(new FmtBool("Y", "N")), // married
77  			new Optional(), // numberOfKids
78  			new NotNull(), // favouriteQuote
79  			new NotNull(), // email
80  			new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
81  		};
82  		
83  		return processors;
84  	}
85  	
86  	/**
87  	 * An example of writing using CsvBeanWriter.
88  	 */
89  	private static void writeWithCsvBeanWriter() throws Exception {
90  		
91  		// create the customer beans
92  		final CustomerBean john = new CustomerBean("1", "John", "Dunbar",
93  			new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(),
94  			"1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null,
95  			"\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L);
96  		final CustomerBean bob = new CustomerBean("2", "Bob", "Down",
97  			new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
98  			"1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0,
99  			"\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L);
100 		final List<CustomerBean> customers = Arrays.asList(john, bob);
101 		
102 		ICsvBeanWriter beanWriter = null;
103 		try {
104 			beanWriter = new CsvBeanWriter(new FileWriter("target/writeWithCsvBeanWriter.csv"),
105 				CsvPreference.STANDARD_PREFERENCE);
106 			
107 			// the header elements are used to map the bean values to each column (names must match)
108 			final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate",
109 				"mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" };
110 			final CellProcessor[] processors = getProcessors();
111 			
112 			// write the header
113 			beanWriter.writeHeader(header);
114 			
115 			// write the beans
116 			for( final CustomerBean customer : customers ) {
117 				beanWriter.write(customer, header, processors);
118 			}
119 			
120 		}
121 		finally {
122 			if( beanWriter != null ) {
123 				beanWriter.close();
124 			}
125 		}
126 	}
127 	
128 	/**
129 	 * An example of writing using CsvResultSetWriter
130 	 */
131 	private static void writeWithResultSetWriter() throws Exception {
132 		// create ResultSet mock
133 		final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate",
134 			"mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" };
135 		final Object[][] johnData = new Object[][] {{"1", "John", "Dunbar",
136 			new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(),
137 			"1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null,
138 			"\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L}};
139 		final ResultSet john = new ResultSetMock(johnData, header);
140 		final Object[][] bobData = new Object[][] {{"2", "Bob", "Down",
141 			new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
142 			"1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0,
143 			"\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L}};
144 		final ResultSet bob = new ResultSetMock(bobData, header);
145 		
146 		ICsvResultSetWriter resultSetWriter = null;
147 		try {
148 			resultSetWriter = new CsvResultSetWriter(new FileWriter("target/writeWithCsvResultSetWriter.csv"),
149 				CsvPreference.STANDARD_PREFERENCE);
150 			final CellProcessor[] processors = getProcessors();
151 			
152 			// writer csv file from ResultSet
153 			resultSetWriter.write(john, processors);
154 			resultSetWriter.write(bob, processors);
155 		} finally {
156 			if ( resultSetWriter != null ) {
157 				resultSetWriter.close();
158 			}
159 		}
160 	}
161 	
162 	/**
163 	 * An example of reading using CsvListWriter.
164 	 */
165 	private static void writeWithCsvListWriter() throws Exception {
166 		
167 		// create the customer Lists (CsvListWriter also accepts arrays!)
168 		final List<Object> john = Arrays.asList(new Object[] { "1", "John", "Dunbar",
169 			new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(),
170 			"1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null,
171 			"\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L });
172 		
173 		final List<Object> bob = Arrays.asList(new Object[] { "2", "Bob", "Down",
174 			new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
175 			"1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0,
176 			"\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L });
177 		
178 		ICsvListWriter listWriter = null;
179 		try {
180 			listWriter = new CsvListWriter(new FileWriter("target/writeWithCsvListWriter.csv"),
181 				CsvPreference.STANDARD_PREFERENCE);
182 			
183 			final CellProcessor[] processors = getProcessors();
184 			final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate",
185 				"mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" };
186 			
187 			// write the header
188 			listWriter.writeHeader(header);
189 			
190 			// write the customer lists
191 			listWriter.write(john, processors);
192 			listWriter.write(bob, processors);
193 			
194 		}
195 		finally {
196 			if ( listWriter != null ) {
197 				listWriter.close();
198 			}
199 		}
200 	}
201 	
202 	/**
203 	 * An example of reading using CsvMapWriter.
204 	 */
205 	private static void writeWithCsvMapWriter() throws Exception {
206 		
207 		final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress",
208 			"married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" };
209 		
210 		// create the customer Maps (using the header elements for the column keys)
211 		final Map<String, Object> john = new HashMap<String, Object>();
212 		john.put(header[0], "1");
213 		john.put(header[1], "John");
214 		john.put(header[2], "Dunbar");
215 		john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime());
216 		john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States");
217 		john.put(header[5], null);
218 		john.put(header[6], null);
219 		john.put(header[7], "\"May the Force be with you.\" - Star Wars");
220 		john.put(header[8], "jdunbar@gmail.com");
221 		john.put(header[9], 0L);
222 		
223 		final Map<String, Object> bob = new HashMap<String, Object>();
224 		bob.put(header[0], "2");
225 		bob.put(header[1], "Bob");
226 		bob.put(header[2], "Down");
227 		bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime());
228 		bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States");
229 		bob.put(header[5], true);
230 		bob.put(header[6], 0);
231 		bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind");
232 		bob.put(header[8], "bobdown@hotmail.com");
233 		bob.put(header[9], 123456L);
234 		
235 		ICsvMapWriter mapWriter = null;
236 		try {
237 			mapWriter = new CsvMapWriter(new FileWriter("target/writeWithCsvMapWriter.csv"),
238 				CsvPreference.STANDARD_PREFERENCE);
239 			
240 			final CellProcessor[] processors = getProcessors();
241 			
242 			// write the header
243 			mapWriter.writeHeader(header);
244 			
245 			// write the customer maps
246 			mapWriter.write(john, header, processors);
247 			mapWriter.write(bob, header, processors);
248 			
249 		}
250 		finally {
251 			if( mapWriter != null ) {
252 				mapWriter.close();
253 			}
254 		}
255 	}
256 	
257 	/**
258 	 * An example of partial reading using CsvBeanWriter.
259 	 */
260 	private static void partialWriteWithCsvBeanWriter() throws Exception {
261 		
262 		// create the customer beans
263 		final CustomerBean john = new CustomerBean("1", "John", "Dunbar",
264 			new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(),
265 			"1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null,
266 			"\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L);
267 		final CustomerBean bob = new CustomerBean("2", "Bob", "Down",
268 			new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
269 			"1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0,
270 			"\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L);
271 		final List<CustomerBean> customers = Arrays.asList(john, bob);
272 		
273 		ICsvBeanWriter beanWriter = null;
274 		try {
275 			beanWriter = new CsvBeanWriter(new FileWriter("target/partialWriteWithCsvBeanWriter.csv"),
276 				CsvPreference.STANDARD_PREFERENCE);
277 			
278 			// only map 5 of the 10 fields
279 			final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" };
280 			
281 			// assign a default value for married (if null), and write numberOfKids as an empty column if null
282 			final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(),
283 				new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() };
284 			
285 			// write the header
286 			beanWriter.writeHeader(header);
287 			
288 			// write the customer beans
289 			for( final CustomerBean customer : customers ) {
290 				beanWriter.write(customer, header, processors);
291 			}
292 			
293 		}
294 		finally {
295 			if( beanWriter != null ) {
296 				beanWriter.close();
297 			}
298 		}
299 	}
300 	
301 	/**
302 	 * An example of partial reading using CsvListWriter.
303 	 */
304 	private static void partialWriteWithCsvListWriter() throws Exception {
305 		
306 		final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" };
307 		
308 		// create the customer Lists (CsvListWriter also accepts arrays!)
309 		final List<Object> john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null});
310 		final List<Object> bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 });
311 		
312 		ICsvListWriter listWriter = null;
313 		try {
314 			listWriter = new CsvListWriter(new FileWriter("target/partialWriteWithCsvListWriter.csv"),
315 				CsvPreference.STANDARD_PREFERENCE);
316 			
317 			// assign a default value for married (if null), and write numberOfKids as an empty column if null
318 			final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(),
319 				new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() };
320 			
321 			// write the header
322 			listWriter.writeHeader(header);
323 			
324 			// write the customer Lists
325 			listWriter.write(john, processors);
326 			listWriter.write(bob, processors);
327 			
328 		}
329 		finally {
330 			if( listWriter != null ) {
331 				listWriter.close();
332 			}
333 		}
334 	}
335 	
336 	/**
337 	 * An example of partial reading using CsvMapWriter.
338 	 */
339 	private static void partialWriteWithCsvMapWriter() throws Exception {
340 		
341 		final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" };
342 		
343 		// create the customer Maps (using the header elements for the column keys)
344 		final Map<String, Object> john = new HashMap<String, Object>();
345 		john.put(header[0], "1");
346 		john.put(header[1], "John");
347 		john.put(header[2], "Dunbar");
348 		john.put(header[3], null);
349 		john.put(header[4], null);
350 		
351 		final Map<String, Object> bob = new HashMap<String, Object>();
352 		bob.put(header[0], "2");
353 		bob.put(header[1], "Bob");
354 		bob.put(header[2], "Down");
355 		bob.put(header[3], true);
356 		bob.put(header[4], 0);
357 		
358 		ICsvMapWriter mapWriter = null;
359 		try {
360 			mapWriter = new CsvMapWriter(new FileWriter("target/partialWriteWithCsvMapWriter.csv"),
361 				CsvPreference.STANDARD_PREFERENCE);
362 			
363 			// assign a default value for married (if null), and write numberOfKids as an empty column if null
364 			final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(),
365 				new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null };
366 			
367 			// write the header
368 			mapWriter.writeHeader(header);
369 			
370 			// write the customer Maps
371 			mapWriter.write(john, header, processors);
372 			mapWriter.write(bob, header, processors);
373 			
374 		}
375 		finally {
376 			if( mapWriter != null ) {
377 				mapWriter.close();
378 			}
379 		}
380 	}
381 	
382 }