As the documentation states, when you give a List<String> it'll use it a one record, ie one row, ie each String in a cell.
If the given collection only contains simple objects, this method will print a single record like printRecord(Iterable)
You need a code that use the fact that each String is in fact a row, like
passing each
Stringsplitted a separate recordList<String> myList = new ArrayList<>(); for (String row : myList) csvPrinter.printRecord(row.split(","));Split all
Stringthen pass the whole list as a list of recordsList<String> myList = new ArrayList<>(); List<String[]> myListSplitted = myList.stream().map(row -> row.split(",")).collect(Collectors.toList()); csvPrinter.printRecords(myListSplitted);
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVPrinter.html
CSVPrinter (Apache Commons CSV 1.14.2-SNAPSHOT API)
Example: try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) { printer.printRecord("id", "userName", "firstName", "lastName", "birthday"); printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15)); printer.println(); printer.printRecord(2, ...
Baeldung
baeldung.com › home › java › java io › introduction to apache commons csv
Introduction to Apache Commons CSV | Baeldung
January 8, 2024 - There are different types of CSVFormat specifying the format of the CSV file, an example of which you can see in the next paragraph. Let’s see how we can create the same CSV file as above: @Test void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { StringWriter sw = new StringWriter(); CSVFormat csvFormat = CSVFormat.DEFAULT.builder() .setHeader(HEADERS) .build(); try (final CSVPrinter printer = new CSVPrinter(sw, csvFormat)) { AUTHOR_BOOK_MAP.forEach((author, title) -> { try { printer.printRecord(author, title); } catch (IOException e) { e.printStackTrace(); } }); } assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); }
Java Tips
javatips.net › api › org.apache.commons.csv.csvprinter
Java Examples for org.apache.commons.csv.CSVPrinter
Example 7 · private void exportTo(File file, Predicate<Integer> filter) throws IOException { CSVStrategy strategy = new CSVStrategy(';', '"', CSVStrategy.COMMENTS_DISABLED, CSVStrategy.ESCAPE_DISABLED, false, false, false, false); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { CSVPrinter printer = new CSVPrinter(writer); printer.setStrategy(strategy); printer.println(new String[] { // Messages.CSVColumn_Date, // Messages.CSVColumn_Value, // Messages.CSVColumn_Transferals, // Messages.CSVColumn_DeltaInPercent, Messages.CSVColumn_CumulatedPerf
Stack Overflow
stackoverflow.com › questions › 71378344 › csvprinter-java
csv - CSVPrinter java - Stack Overflow
Here is a quick example : BufferedWriter successWriter = Files.newBufferedWriter(Paths.get( "C:\\temp\\testingtest.csv")); char delimiter = ';'; CSVPrinter csvPrinter = new CSVPrinter(successWriter, // Creates a new default builder.
CalliCoder
callicoder.com › java-read-write-csv-file-apache-commons-csv
Read / Write CSV files in Java using Apache Commons CSV | CalliCoder
February 18, 2022 - Finally, Let’s see an example of generating a CSV file with Apache Commons CSV. import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; public class CSVWriter { private static final String SAMPLE_CSV_FILE = "./sample.csv"; public static void main(String[] args) throws IOException { try ( BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Name", "Designation",
Java2s
java2s.com › example › java-api › org › apache › commons › csv › csvprinter › println-0-0.html
Example usage for org.apache.commons.csv CSVPrinter println
public static void write(Writer writer, DataGroup data, CSVFormat format) throws IOException { BufferedWriter outf = new BufferedWriter(writer, IpacTableUtil.FILE_IO_BUFFER_SIZE); try {/*from w w w .j a va2 s. c o m*/ CSVPrinter printer = new CSVPrinter(outf, format); if (data != null && ...
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-apache-commons-csv
Reading and Writing CSVs in Java with Apache Commons CSV
February 20, 2019 - CSVPrinter csvPrinter = new CSVPrinter(stringWriter, CSVFormat.DEFAULT.withHeader("Index", "Girth", "Height", "Volume")); csvPrinter.printRecord("1", "8.3", "70", "10.3"); csvPrinter.flush();
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVPrinter.java.html
CSVPrinter.java - Apache Commons
* </p> * * <p>Example:</p> * * <pre> * try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) { * printer.printRecord("id", "userName", "firstName", "lastName", "birthday"); * printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15)); * printer.println(); * printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29)); * } catch (IOException ex) { * ex.printStackTrace(); * } * </pre> * * <p>This code will write the following to csv.txt:</p> * <pre> * id,userName,firstName,lastName,birthday * 1,john73,John,Doe,1973-09-15 * * 2,mary,Mary,Meyer,1985-03-29 * </pre> */ public final class CSVPrinter implements Flushable, Closeable { /** The place that the values get written.
Program Creek
programcreek.com › java-api-examples
org.apache.commons.csv.CSVPrinter Java Examples
Example #9 · @Override public void writeValueTo(CsvWriter context, Type type, Object instance) throws Exception { // TODO 处理null CSVPrinter out = context.getOutputStream(); if (instance == null) { out.print(StringUtility.EMPTY); return; } // 处理对象类型 Class<?> clazz = TypeUtility.getRawType(type, null); ClassDefinition definition = context.getClassDefinition(clazz); int length = definition.getProperties().length; out.print(length); for (PropertyDefinition property : definition.getProperties()) { CsvConverter converter = context.getCsvConverter(property.getSpecification()); Object value = property.getValue(instance); converter.writeValueTo(context, property.getType(), value); } } Example #10 ·
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-csv-with-java
Parse and Generate CSV with Java | Parse and Generate Formats
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.List; public class CsvWriterExample { public static void main(String[] args) throws IOException { List<String> headers = Arrays.asList("ID", "Product", "Price"); List<List<String>> records = Arrays.asList( Arrays.asList("1", "Laptop", "1200.50"), Arrays.asList("2", "Keyboard", "75.00") ); try (Writer writer = new FileWriter("output.csv"); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(headers.toArray(new String[0])))) { for (List<String> record : records) { csvPrinter.printRecord(record); } } } }
Java2s
java2s.com › example › java-api › org › apache › commons › csv › csvprinter › csvprinter-2-12.html
Example usage for org.apache.commons.csv CSVPrinter CSVPrinter
c om*/ FileWriter fileWriter; CSVFormat ... = File.createTempFile(TEMP_CSV, EXT, dir); fileWriter = new FileWriter(filename); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); int count = 0; for (Map.Entry entry : annotations.entrySet()) { Annotations votes = (Annotations) ...
Zebra TechDocs
techdocs.zebra.com › link-os › 2-14 › pc_net › content › html › 06c000ce-024d-5d39-608a-98227fe05bf7
CsvPrinter Class
/// /// ^XA^DFE:CnCsvPrinterExampleTemplate.zpl^FS /// ^A@N,75,75,E:ANMDS.TTF^CI28^FO0,100^FN1"Customer Name"^FS /// ^A@N,75,75,E:ANMDS.TTF^FO0,200^FN2"Component Name"^FS^ /// ^A@N,75,75,E:ANMDS.TTF^FO0,300^FN3"Vendor Name"^FS /// ^A@N,75,75,E:ANMDS.TTF^FO0,400^FN4"Vendor ID"^FS /// ^A@N,75,75,E:ANMDS.TTF^FO0,500^FN5"Invoice Number"^FS /// ^XZ private static void CnCsvPrintingExample() { // The possible inputs to the one-line Csv printing function(s) string destinationDevice = "192.168.1.32"; string templateFilename = "C:\\CnCsvPrinterExampleTemplate.zpl"; string defaultQuantityString = "1"; bool verbose = true; // The outputDataStream argument may be null, in which case the data generated by the CsvPrinter class will // not be logged but will be sent to the destination device.
Medium
medium.com › javarevisited › boost-your-productivity-at-csv-files-with-apache-commons-csv-in-java-c52b33037c4c
Boost your Production at CSV files with Apache.commons.CSV in Java
July 18, 2020 - Apache.Commons.CSV offers several methods to read fields at CSV files, in this example, we access the data with header names but it can also be done with index numbers. ... Writing CSV files with Apache.Commons.CSV is just as easy . ... try {FileWriter fileWriter = new FileWriter("./mountains.csv", true);try (CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.RFC4180)) {//HEADER recordcsvPrinter.printRecord("mountain","meters");//DATA recordscsvPrinter.printRecord("Mount Everest","8.848");csvPrinter.printRecord("K2","8.611");csvPrinter.printRecord("Kangchenjunga","8.586");csvPrinter.printRecord("olumpus","2.918");csvPrinter.flush();}} catch (IOException e) {e.printStackTrace();}
GitHub
github.com › apache › commons-csv › blob › master › src › main › java › org › apache › commons › csv › CSVPrinter.java
commons-csv/src/main/java/org/apache/commons/csv/CSVPrinter.java at master · apache/commons-csv
* <p>Example:</p> * * <pre> * try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) { * printer.printRecord("id", "userName", "firstName", "lastName", "birthday"); * printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15)); * printer.println(); * printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29)); * } catch (IOException ex) { * ex.printStackTrace(); * } * </pre> * * <p>This code will write the following to csv.txt:</p> * <pre> * id,userName,firstName,lastName,birthday ·
Author apache
Zebra TechDocs
techdocs.zebra.com › link-os › 2-12 › pc › content › com › zebra › sdk › printer › csvprinter
CsvPrinter (Zebra API (build v2.11.2800))
System.out.println("\nThe outputDataStream argument is null:"); try { CsvPrinter.print(destinationDevice, getSampleCnCsvData(), templateFilename, defaultQuantityString, null, verbose); } catch (Exception e) { e.printStackTrace(); } } private static ByteArrayInputStream getSampleCnCsvData() { String sampleCnCsvData = "东风伟世通汽车饰件系统有限公司,驾驶员侧仪表板下装饰件,供应商名称,供应商代码,订单号\n"; return new ByteArrayInputStream(sampleCnCsvData.getBytes()); } }
Top answer 1 of 3
17
It looks like you are printing all the records on the same line .
Other methods like printRecords will be more helpful :
String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecords(excelParser.getRecords());
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
2 of 3
11
Automatically close & flush
The Answer by Arnaud is correct and good. Here is a variation, shorter and more modern.
Here we:
- Use the
Path,File, andFilesclasses offered by modern Java NIO.2 to make easier work of file-handling. - Use a
BufferedWriterfor better performance with large amounts of data. - Specify the character encoding to be used. Usually UTF-8 is the best. If you do not understand, read this.
- Include the necessary try-catches for file-related exceptions.
- Add try-with-resources syntax to auto-close the file.
- Skip the explicit flushing, as the buffered writer will be flushed automatically as part of auto-closing the
BufferedWriterandCSVPrinter. To quote the Javadoc, callingjava.io.Writer::close“Closes the stream, flushing it first.”.
Code:
CSVFormat format = CSVFormat.EXCEL.withHeader();
Path path = Paths.get( savePath + ".csv" );
try
(
BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
CSVPrinter printer = new CSVPrinter( writer , format ) ;
)
{
printer.printRecords( excelParser.getRecords() );
}
catch ( IOException e )
{
e.printStackTrace();
}
// At this point, the `CSVPrinter` is automatically closed.
// And, ➡️ the `BufferedWriter` is automatically closed and flushed.