| 1 | package net.minecraft.util;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import java.io.IOException;
|
| 5 | import java.io.Writer;
|
| 6 | import java.util.List;
|
| 7 | import java.util.stream.Collectors;
|
| 8 | import java.util.stream.Stream;
|
| 9 | import org.apache.commons.lang3.StringEscapeUtils;
|
| 10 | import org.jspecify.annotations.Nullable;
|
| 11 |
|
| 12 | public class CsvOutput {
|
| 13 | private static final String LINE_SEPARATOR = "\r\n";
|
| 14 | private static final String FIELD_SEPARATOR = ",";
|
| 15 | private final Writer output;
|
| 16 | private final int columnCount;
|
| 17 |
|
| 18 | private CsvOutput(final Writer output, final List<String> headers) throws IOException {
|
| 19 | this.output = output;
|
| 20 | this.columnCount = headers.size();
|
| 21 | this.writeLine(headers.stream());
|
| 22 | }
|
| 23 |
|
| 24 | public static CsvOutput.Builder builder() {
|
| 25 | return new CsvOutput.Builder();
|
| 26 | }
|
| 27 |
|
| 28 | public void writeRow(final @Nullable Object... values) throws IOException {
|
| 29 | if (values.length != this.columnCount) {
|
| 30 | throw new IllegalArgumentException("Invalid number of columns, expected " + this.columnCount + ", but got " + values.length);
|
| 31 | }
|
| 32 |
|
| 33 | this.writeLine(Stream.of(values));
|
| 34 | }
|
| 35 |
|
| 36 | private void writeLine(final Stream<? extends @Nullable Object> values) throws IOException {
|
| 37 | this.output.write(values.map(CsvOutput::getStringValue).collect(Collectors.joining(",")) + "\r\n");
|
| 38 | }
|
| 39 |
|
| 40 | private static String getStringValue(final @Nullable Object value) {
|
| 41 | return StringEscapeUtils.escapeCsv(value != null ? value.toString() : "[null]");
|
| 42 | }
|
| 43 |
|
| 44 | public static class Builder {
|
| 45 | private final List<String> headers = Lists.newArrayList();
|
| 46 |
|
| 47 | public CsvOutput.Builder addColumn(final String header) {
|
| 48 | this.headers.add(header);
|
| 49 | return this;
|
| 50 | }
|
| 51 |
|
| 52 | public CsvOutput build(final Writer writer) throws IOException {
|
| 53 | return new CsvOutput(writer, this.headers);
|
| 54 | }
|
| 55 | }
|
| 56 | }
|
| 57 |
|