CSVWriter extends AbstractDataWriter { public void write(DataSource data, OutputStream output) throws IOException { Character separator = getSetting(SEPARATOR_CHAR); OutputStreamWriter writer = new OutputStreamWriter(output); int i = 0; int colCount = data.getColumnCount(); for (Comparable<?> cell : data) { writer.write(String.valueOf(cell)); int col = i % colCount; if (col < colCount - 1) { writer.write(separator); } else { writer.write("\r\n"); } i++; } writer.close(); } CSVWriter(String mimeType); void write(DataSource data, OutputStream output); static final String SEPARATOR_CHAR; }
@Test public void testWriter() throws IOException { String[] formats = { "text/csv", "text/tab-separated-values" }; String[] expected = { "0.0,10.0,20\r\n" + "1.0,11.0,21\r\n" + "2.0,12.0,22\r\n", "0.0\t10.0\t20\r\n" + "1.0\t11.0\t21\r\n" + "2.0\t12.0\t22\r\n", }; for (int i = 0; i < formats.length; i++) { DataWriter writer = DataWriterFactory.getInstance().get(formats[i]); OutputStream output = new ByteArrayOutputStream(); writer.write(data, output); assertEquals(expected[i], output.toString()); } }
@Test public void testSeparator() throws IOException { OutputStream output = new ByteArrayOutputStream(); DataWriter writer = DataWriterFactory.getInstance().get("text/csv"); writer.setSetting(CSVWriter.SEPARATOR_CHAR, ';'); writer.write(data, output); assertEquals( "0.0;10.0;20\r\n" + "1.0;11.0;21\r\n" + "2.0;12.0;22\r\n", output.toString() ); }