CsvFormatter { public String format(Row row) { StringBuilder sbd = new StringBuilder(); for (int i = 0; i < row.getArity(); i++) { if (i > 0) { sbd.append(fieldDelim); } Object v = row.getField(i); if (v == null) { continue; } if (quoteChar != null && types[i].equals(Types.STRING)) { String str = (String) v; if (str.isEmpty() || str.contains(fieldDelim) || str.contains(quoteChar)) { sbd.append(quoteChar); sbd.append(str.replace(quoteChar, escapeChar + quoteChar)); sbd.append(quoteChar); } else { sbd.append(v.toString()); } } else { sbd.append(v.toString()); } } return sbd.toString(); } CsvFormatter(TypeInformation[] types, String fieldDelim, @Nullable Character quoteChar); String format(Row row);  }
@Test public void testFormatter() throws Exception { TypeInformation[] types = new TypeInformation[]{Types.STRING, Types.DOUBLE, Types.LONG, Types.BOOLEAN, Types.SQL_TIMESTAMP}; Row row = Row.of("string", 1.0, 1L, true, new java.sql.Timestamp(System.currentTimeMillis())); CsvFormatter formatter = new CsvFormatter(types, ",", '"'); CsvParser parser = new CsvParser(types, ",", '"'); String text = formatter.format(row); Row parsed = parser.parse(text).f1; Assert.assertEquals(parsed.getArity(), row.getArity()); for (int i = 0; i < parsed.getArity(); i++) { Assert.assertEquals(parsed.getField(i), row.getField(i)); } }
@Test public void testDoublePrecision() throws Exception { TypeInformation[] types = new TypeInformation[]{Types.DOUBLE}; CsvFormatter formatter = new CsvFormatter(types, ",", '"'); CsvParser parser = new CsvParser(types, ",", '"'); Double[] values = new Double[]{Double.MAX_VALUE, Double.MIN_VALUE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, new Random().nextDouble()}; for (Double v : values) { String text = formatter.format(Row.of(v)); Row parsed = parser.parse(text).f1; Double p = (Double) parsed.getField(0); Assert.assertEquals(v, p, 0.); } }