View Javadoc

1   package au.com.bytecode.opencsv;
2   
3   /**
4    Copyright 2005 Bytecode Pty Ltd.
5   
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9   
10   http://www.apache.org/licenses/LICENSE-2.0
11  
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17   */
18  
19  import static org.junit.Assert.assertTrue;
20  
21  import java.io.File;
22  import java.io.FileReader;
23  import java.io.FileWriter;
24  import java.io.IOException;
25  
26  import org.junit.Before;
27  import org.junit.Test;
28  
29  public class OpencsvTest {
30  
31  	private File tempFile = null;
32  	private CSVWriter writer = null;
33  	private CSVReader reader = null;
34  
35  	@Before
36  	public void setUp() throws IOException {
37  		tempFile = File.createTempFile("csvWriterTest", ".csv");
38  		tempFile.deleteOnExit();
39  	}
40  
41  	/**
42  	 * Test the full cycle of write-read
43  	 * 
44  	 */
45  	@Test
46  	public void testWriteRead() throws IOException {
47  		final String[][] data = new String[][]{{"hello, a test", "one nested \" test"}, {"\"\"", "test", null, "8"}};
48  
49  		writer = new CSVWriter(new FileWriter(tempFile));
50  		for (int i = 0; i < data.length; i++) {
51  			writer.writeNext(data[i]);
52  		}
53  		writer.close();
54  
55  		reader = new CSVReader(new FileReader(tempFile));
56  
57  		String[] line;
58  		for (int row = 0; (line = reader.readNext()) != null; row++) {
59  			assertTrue(line.length == data[row].length);
60  
61  			for (int col = 0; col < line.length; col++) {
62  				if (data[row][col] == null) {
63  					assertTrue(line[col].equals(""));
64  				} else {
65  					assertTrue(line[col].equals(data[row][col]));
66  				}
67  			}
68  		}
69  
70  		reader.close();
71  	}
72  }