Java read CSV File 📰

Published: 06 July 2020
on channel: Bro Code
94,128
2.1k

IMPORTANT NOTE: If values in your CSV contain commas naturally, they will be split. (Ex. $1,000). If this is the case, replace:

String[] row = line.split(",");
with
String[] row = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

^ This is regex and is very complicated. It looks for string patterns. Explaining this requires another video entirely.
//******************************************************
import java.io.*;

public class Main {

public static void main(String[] args) {

//CSV = Comma-Separated Values
// text file that uses a comma to separate values

String file = "src\\students.csv";
BufferedReader reader = null;
String line = "";

try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {

String[] row = line.split(",");
//String[] row = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
//use this if your values already contain commas
for(String index : row) {
System.out.printf("%-10s", index);
}
System.out.println();
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//******************************************************


On this page of the site you can watch the video online Java read CSV File 📰 with a duration of hours minute second in good quality, which was uploaded by the user Bro Code 06 July 2020, share the link with friends and acquaintances, this video has already been watched 94,128 times on youtube and it was liked by 2.1 thousand viewers. Enjoy your viewing!