Created
October 18, 2022 13:41
-
-
Save julianjupiter/5c4c99412cd6f1af2f0e60a699644159 to your computer and use it in GitHub Desktop.
Create CSV file in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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