Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Created October 18, 2022 13:41
Show Gist options
  • Save julianjupiter/5c4c99412cd6f1af2f0e60a699644159 to your computer and use it in GitHub Desktop.
Save julianjupiter/5c4c99412cd6f1af2f0e60a699644159 to your computer and use it in GitHub Desktop.
Create CSV file in Java
package app;
import com.julianjupiter.csv.CsvWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
public class CsvApp {
public static void main(String[] args) throws IOException {
var data = List.of(
new String[]{"1", "Maria Clara"},
new String[]{"2", "Ibarra"}
);
var file = Paths.get("file.csv");
var writer = CsvWriter.create(file, data);
writer.write();
}
}
package com.julianjupiter.csv;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CsvWriter {
private static final String DEFAULT_DELIMITER = ",";
private String delimiter = DEFAULT_DELIMITER;
private final Path file;
private final List<String[]> data;
private CsvWriter(Path file, List<String[]> data) {
this.file = file;
this.data = data;
}
public static CsvWriter create(Path file, List<String[]> data) {
return new CsvWriter(file, data);
}
public CsvWriter delimiter(String delimiter) {
this.delimiter = delimiter;
return this;
}
public void write() throws IOException {
var csvOutputFile = this.file.toFile();
try (var pw = new PrintWriter(csvOutputFile)) {
this.data.stream()
.map(this::convert)
.forEach(pw::println);
}
}
private String convert(String[] line) {
return Arrays.stream(line)
.map(this::escapeSpecialCharacters)
.collect(Collectors.joining(this.delimiter));
}
private String escapeSpecialCharacters(String data) {
if (data == null) {
return null;
}
var escapedData = data.replaceAll("\\R", " ");
if (data.contains(this.delimiter) || data.contains("\"") || data.contains("'")) {
data = data.replace("\"", "\"\"");
escapedData = "\"" + data + "\"";
}
return escapedData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment