Java Guide: How to Read CSV Files Correctly πŸ“„

Learn the essential tips for reading CSV files in Java, including handling commas within data values to ensure accurate parsing.

Java Guide: How to Read CSV Files Correctly πŸ“„
Bro Code
110.6K views β€’ Jul 6, 2020
Java Guide: How to Read CSV Files Correctly πŸ“„

About this video

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();
}
}
}
}
//******************************************************

Tags and Topics

Browse our collection to discover more content in these categories.

Video Information

Views

110.6K

Likes

2.6K

Duration

9:12

Published

Jul 6, 2020

User Reviews

4.7
(22)
Rate:

Related Trending Topics

LIVE TRENDS

Related trending topics. Click any trend to explore more videos.

Trending Now