fix CSV generation

This commit is contained in:
Jörg Prante 2022-05-30 17:20:31 +02:00
parent 78835f875b
commit 31f27e33ef
2 changed files with 35 additions and 9 deletions

View file

@ -37,19 +37,20 @@ public class Generator implements Constants, Closeable, Flushable {
return this;
}
public void write(String value) throws IOException {
public synchronized void write(String value) throws IOException {
if (col >= keys.size()) {
writer.write(LF);
row++;
col = 0;
} else {
if (col > 0) {
writer.write(COMMA);
}
}
if (value != null) {
writer.write(escape(value));
}
col++;
if (col > keys.size()) {
writer.write(LF);
row++;
col = 0;
}
}
public int getColumn() {

View file

@ -10,7 +10,32 @@ import java.util.Arrays;
public class GeneratorTest {
@Test
public void test() throws IOException {
public void testOneColumn() throws IOException {
StringWriter writer = new StringWriter();
Generator gen = new Generator(writer);
gen.keys(Arrays.asList("a"));
for (int i = 0; i < 2; i++) {
gen.write("val" + i);
}
gen.close();
assertEquals("val0\nval1", writer.toString());
}
@Test
public void testTwoColumns() throws IOException {
StringWriter writer = new StringWriter();
Generator gen = new Generator(writer);
gen.keys(Arrays.asList("a", "b"));
for (int i = 0; i < 2; i++) {
gen.write("val" + i);
gen.write("val" + i);
}
gen.close();
assertEquals("val0,val0\nval1,val1", writer.toString());
}
@Test
public void testThreeColumns() throws IOException {
StringWriter writer = new StringWriter();
Generator gen = new Generator(writer);
gen.keys(Arrays.asList("a", "b", "c"));