Created
May 15, 2013 06:05
-
-
Save roufiq/5581925 to your computer and use it in GitHub Desktop.
Contoh source code untuk membaca file CSV di Java dengan menggunakan library OpenCSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import au.com.bytecode.opencsv.CSVReader; | |
import au.com.bytecode.opencsv.CSVWriter; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.io.StringWriter; | |
import java.util.List; | |
/** | |
* | |
* @author roufiq | |
*/ | |
public class ReaderExample { | |
private static final String ADDRESS_FILE = "daftar_nama.csv"; | |
public static void main(String[] args) { | |
try { | |
// baca file dengan parameter file, separator, dan quotechar | |
CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE), ',', '\"'); | |
// baca file utuh | |
List<String[]> readAll = reader.readAll(); | |
StringWriter sw = new StringWriter(); | |
CSVWriter writer = new CSVWriter(sw); | |
writer.writeAll(readAll); | |
System.out.println("\n\n File CSV File awal :\n"); | |
System.out.println(sw.toString()); | |
// baca per field | |
String[] nextLine; | |
CSVReader readerField = new CSVReader(new FileReader(ADDRESS_FILE), ',', '\"'); | |
while ((nextLine = readerField.readNext()) != null) { | |
System.out.println("Nama Lengkap: [" + nextLine[0] | |
+ "]\nNama Panggilan : [" + nextLine[1] | |
+ "]\nJenis Kelamin: [" + nextLine[2] + "]" | |
+ "]\nTanggal Lahir: [" + nextLine[3] + "]" | |
+ "]\nTempat Lahir: [" + nextLine[4] + "]\n"); | |
} | |
} | |
// jika file CSV tidak ditemukan | |
catch (IOException e) { | |
System.out.println("File tidak ditemukan"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment