In this example, let’s see how to read and parse CSV file in Java.
Source Code
(1) Read CSV File To Java
package com.beginner.examples;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import com.csvreader.CsvReader;
/**
* @desc Read CSV files
*/
public class ReadCSV {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("E:tmptest.csv");
CsvReader reader = new CsvReader(fileReader,',');
ArrayList csvList = new ArrayList();
while(reader.readRecord()) {
csvList.add(reader.getValues());
}
reader.close();
for(int row=0; row<csvList.size(); row++) {
System.out.print(csvList.get(row)[0] + ",");
System.out.print(csvList.get(row)[1] + ",");
System.out.println(csvList.get(row)[2] + ",");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
name,age,address,
Alic,18,Shanghai,
(2) Write Data from Java To CSV File
package com.beginner.examples;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteCSV {
public static void main(String[] args) {
try {
File csv = new File("E:tmptest.csv");
BufferedWriter writer = new BufferedWriter(new FileWriter(csv, true));
writer.write(""Bob"" + "," + ""2000"" + "," + ""2004"");
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
References
Imported packages in Java documentation: