Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

March 14, 2025

Java: Exporting data to CSV files

The Comma Separated Value CSV format is a very easy to use and flexible format to save data to files. Many programs like Excel or Calc can import csv files and work with the data.

In this article you find a possible implementation for Java for exporting CSV files. You may use this Java class in your code and adjust it to your use case.

Below the code you find some useful hints on how to handle CSV files properly.

CSV file export in Java

You can take the following class and copy it into your Java project.

Your data should exist in some sort of two dimensional representation like a two dimensional list.

You may change the datatype of the implementation. Please note that we use the .toString() mehtod in the example code which may not always be the method of choice!

The class CsvWriter is writing the lists one by one comma separated in one line. For every new list there is a carriage return line feed.

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 *
 * @author Matthias Schoepe - Computer-Masters.net
 */
public class CsvWriter {

    private final String CRLF = "\r\n";
    private String delimiter = ",";

    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    public void exportCsv(List<List<Integer>> twoDimensionalData, String filename) {
        try {
            FileWriter writer = new FileWriter(filename);

            for (int i = 0; i < twoDimensionalData.size(); i++) {
                for (int j = 0; j < twoDimensionalData.get(i).size(); j++) {
                    writer.append(
                            //NOTE: for demonstration purposes we use the toString() method
                            twoDimensionalData.get(i).get(j).toString()
                            //use an alternative to toString() if it is not implemented as needed.
                            );
                
                    //Don't forget the delimiter
                    if (j < twoDimensionalData.get(i).size() - 1) {
                        writer.append(delimiter);
                    }
                }
                //Add delimiter and end of the line
                if (i < twoDimensionalData.size() - 1) {
                    writer.append(delimiter + CRLF);
                }
            }

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

The following example shows how to use the CsvWriter class:

//Instantiate the CsvWriter
 CsvWriter writer = new CsvWriter();
        
        //Create some random example data
        Random random = new Random(42);
        List<List<Integer>> test2DimData = new ArrayList<>();
        for(int i=0; i<100; i++) {
            test2DimData.add(new ArrayList<Integer>());
            for(int j=0; j<100; j++) {
                test2DimData.get(i).add(random.nextInt());
            }
        }
        
    //export them to a csv file
    writer.exportCsv(test2DimData, "testExport.csv"); 

Useful knowledge about CSV files

When dealing with CSV files you should keep a few things in mind:

CSV is the acronym for Comma Separated Values. This name implies the main idea behind this file format: Data is to be written in a file spearated by comma as delimiter.

But you may use any other delimiter than a comma. Another common variant is to use the tabulator “\t” as delimiter or the semicolon “;”. Furthermore the end of a line (carriage return, line feed CRLF) has an important meaning in a CSV file.

When looking for a delimiter symbol, make sure the symbol exists in the encoding you use to save the CSV file (UTF-8, ASCII, …). 

Furthermore make sure not to interfere in your data by using ambiguous delimiter symbols. If you have floating point numbers in your data for example it may not be a good idea to use “.” or “,” as a delimiter as the example shows:

1234,567 , 789,2139 would be interpreted as 1234 and 567 and 789 and 2139
1234.567 , 789.2139 would be interpreted as 1234.567 and 789.2139

If you can not avoid using a delimiter that my appear in your data (e.g. texts), then you can mask the data. Usually you may use single or double quotation marks to do so.

Importing CSV files

CSV Import in LibreOffice Calc

A lot of programs offer import dialoges to import CSV files. Like the programm Excel or OpenOffice/LibreOffice Calc you can open CSV files by simply clicking on them.

Be aware that different programs may interpred a CSV file in different ways. Get to know about the conventions in a certain program first.

On the left you can see the dialog that opens up when opening a CSV file withLibreOffice Calc. The preview helps to figure out the correct parameters for the import.

This article is also available in German on Computer-Masters.de

You may also be interested in the following articles:

Leave a Reply

Your email address will not be published. Required fields are marked *