How to Export Data From CSV Files in Java

Written by jonah quant
  • Share
  • Tweet
  • Share
  • Email

The comma-separated values, or CSV, format is widely used for data files. A CSV file has data stored in rows and columns; each row is in a separate line in the file, and each column is separated by a comma from the following column in the same row. CSV files are portable across all operating systems. You can have your Java program generate a CSV file as part of its output.

Skill level:
Moderately Easy

Other People Are Reading

Instructions

  1. 1

    Include the following line at the beginning of your Java program:

    import java.io.FileWriter;

  2. 2

    Open the CSV file as the target of a FileWriter by including the following code:

    FileWriter my Writer = new FileWriter("output.csv");

    Replace "output.csv" by the name of the CSV file you want to create.

  3. 3

    Write comma-separated values to the open CSV file by generating output in append mode, as in the following sample code:

    myWriter.append("EmployeeNumber");

    myWriter.append(',');

    myWriter.append("Name");

    myWriter.append('\n');

    myWriter.append("92");

    myWriter.append(',');

    myWriter.append("Elton Fanculo");

    myWriter.append('\n');

    The first group of invocations to the FileWriter.append method writes the column names at the beginning of the CSV file; the second group writes a sample record.

  4. 4

    Commit all updates made on the CSV file to secondary storage by including the following code in your program after all of the contents of the CSV file have been written out:

    myWriter.flush();

    myWriter.close();

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.