Java: Membaca File CSV menggunakan OpenCSV

Berikut cara untuk membaca file CSV dengan menggunakan library OpenCSV.

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import com.opencsv.CSVReader;

public class ReaderCSV3  {
  public static void main(String[] args) throws Exception {
    String file = "src/data.csv";
    String[][] csv = readCSV(file);
    double[][] data = getDouble(csv);

    for (int i = 0; i < data.length; i++) {
      for (int j = 0; j < data[0].length; j++) {
        System.out.print(data[i][j] + "\t");
      }
      System.out.println("");
    }
  }

  public static String[][] readCSV(String fileName) throws Exception {
    try (CSVReader reader = new CSVReader(new BufferedReader(
      new FileReader(fileName)));) {

      List<String[]> lines = reader.readAll();
      String[][] data = new String[lines.size()][];
      data = lines.toArray(new String[lines.size()][]);

      return data;
    }
  }

  public static double[][] getDouble(String[][] data) {
    double[][] dataDouble = new double[data.length][data[0].length];

    for (int i = 0; i < data.length; i++) {
      for (int j = 0; j < data[0].length; j++) {
        dataDouble[i][j] = Double.parseDouble(data[i][j]);
      }
    }

    return dataDouble;
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s