Week 124 — How can one read and write CSV files in Java?
Question of the Week #124
How can one read and write CSV files in Java?
3 Replies
Reading and writing CSV files is possible both using the standard libraries (e.g.
java.io
) and using external libraries.
For example, we might want to save the following record in a CSV file and read it again:
This can be done using the JDK standard libraries by creating a Writer
and saving it line by line:
To read a CSV file corresponding to the code before, the file can be read line by line and split by commas:
However, this code does not address the possibility of commas, quoting, line breaks or backslashes in the input. While it is possible to add validation for that, it is also possible to use external libraries for this task.To write such a CSV file with Apache Commons CSV, one can call the
printRecord
on the CSVFormat
class for every entry:
It can then be read using the CSVFormat.parse
method:
📖 Sample answer from dan1st
It could be done using BufferedReader, FileReader for reading CSV
And
BufferedWriter, FileWriter for writing CSV
Submission from talhah_tahir