How to read the CSV file in Java?
I assume I need to use an InputStream. How do I continue after the InputStream declaration?
InputStream file = item.getInputStream();
How to read the CSV file in Java?
I assume I need to use an InputStream. How do I continue after the InputStream declaration?
InputStream file = item.getInputStream();
For reading the CSV file, you can use the BufferedReader
class:
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("CSV file location"))
);
After that, use StringTokenizer
to read each common separated values from the file, ex.:
if(reader.readLine()!=null) {
StringTokenizer tokens = new StringTokenizer(
// this will read first line and separates values by (,) and stores them in tokens.
(String) reader.readLine(), ",");
tokens.nextToken(); // this method will read the tokens values on each call.
}
For example, the CSV file is having record of a employee, like:
ram,101
tokens.nextToken()
call will return ram
.tokens.nextToken()
call will return 101
.I recommend https://commons.apache.org/proper/commons-csv/
"Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format."