Wednesday, June 15, 2016

Java to read csv file

This example show how to read csv file using Java.


Prepare:
- Create a spreadsheet:


- Export as csv file:


- The exported csv file in text format:


Using java to read the csv file and print the content:
package javareadcsv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaReadCSV {
    
    static String CsvFile = "/home/buddy/test/test.csv";
    static String FieldDelimiter = ",";

    public static void main(String[] args) throws IOException {
        BufferedReader br;
        
        try {
            br = new BufferedReader(new FileReader(CsvFile));
            
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(FieldDelimiter, -1);
                System.out.print(fields.length + "-");
                for(String s : fields){
                    System.out.print(s);
                    System.out.print(":");
                }
                System.out.println();
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaReadCSV.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        
    }
    
}



To display the content with JavaFX TableView, read next post.

No comments:

Post a Comment