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