Posted by Marta on December 18, 2020 Viewed 4558 times
This article will show you all you need to know to work with a CSV file in Java. You will see how to read data from a file and how to write to a file.
Writing and reading a file is also known as deserializing and serialize. Both are widespread tasks, necessary when you need to persist your data. Let’s say, for instance, you are looping through the products of a website. You could grab this data and save it in a CSV file. Afterward, you could open this file with Excel to analyze the prices.
A CSV file is a file where the data are separated by commas, as follows:
employees.csv
Robert Smith, 30, Sales Assistant Kate Court, 26, Receptionist Steve Roberts, 32, Driver
Let’s see how we can read and write the data of this CSV files in Java.
A simple solution to read data of a file is using the BufferedReader.readLine()
method. First, you will need to open the file for reading using the method Files.newBufferedReader()
. This method returns a BufferedReader
to read text from the file. Next, you can utilize the BufferedReader.readLine()
and read each line of the file. Let’s see this in action below:
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class CSVFileHelper { public List<String> readLinesFromCSVFile(String path) throws IOException { Path filePath = Paths.get(path); List<String> results = new ArrayList<>(); try(BufferedReader buffer = Files.newBufferedReader(filePath, Charset.defaultCharset())){ String line = ""; while((line = buffer.readLine()) != null){ results.add(line); } } return results; } }
You check if the code above works, add the following method to the class CSVFileHelper
. This code will open the employees.csv
, read all lines from the file, and print out the first line. See how this will work in Java :
public static void main(String[] args) throws IOException { List<String> lines = new CSVFileHelper().readLinesFromCSVFile("employees.csv"); System.out.println(lines.get(0)); }
Output:
Robert Smith, 30, Sales Assistant
After running the above code, you might encounter the following error:
Exception in thread "main" java.nio.file.NoSuchFileException: employee.csv at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107) at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214) at java.nio.file.Files.newByteChannel(Files.java:361) at java.nio.file.Files.newByteChannel(Files.java:407) at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384) at java.nio.file.Files.newInputStream(Files.java:152) at java.nio.file.Files.newBufferedReader(Files.java:2784) at cvsfile.CSVFileHelper.readLinesFromCSVFile(CSVFileHelper.java:17) at cvsfile.CSVFileHelper.main(CSVFileHelper.java:29)
This error means that Java couldn’t find the employees.csv
file. Usually, this happens because the indicated path doesn’t correspond with the real file location. By default, Java will look for the file within your project folder, using the root project as the origin. As a result, if the path is “employees.csv”, you should place this file at the project root. See the image below:
Let’s suppose that as new employees join your company, you would like to add them to your employees.csv
to keep track. Therefore you need to write to the CVS file. In Java, you can export data to a file using the BufferedWriter
class and the method BufferedWriter.append()
. The append() method will add any text you pass in at the end of the file.
You can create a BufferedWriter using the method Files.newBufferedWriter()
, indicating the mode you want to use: WRITE, APPEND, CREATE, CREATE_NEW … in this case, since I want to add text at the end of the file, APPEND will work correctly. Note the method Files.newBufferedWriter()
was included in Java 8; it won’t be available in earlier Java versions.
public void writeLinesToCSVFile(String path, String... lines) throws IOException { Path filePath = Paths.get(path); try(BufferedWriter buffer = Files.newBufferedWriter(filePath, Charset.defaultCharset(), StandardOpenOption.APPEND)){ buffer.newLine(); for(String line:lines){ buffer.append(line); buffer.newLine(); } } }
Note the code above won’t start adding the content on a new line; instead it will start writing right after the last character. Therefore; if you want to add a line, you need to add it yourself using the .newline()
method.
To check the above code works correctly, use the following piece of code:
public static void main(String[] args) throws IOException { new CSVFileHelper().writeLinesToCSVFile("employees.csv", "Marta,32,Assistant", "Jessica,35,Actor"); List<String> lines = new CSVFileHelper().readLinesFromCSVFile("employees.csv"); System.out.println(lines.get(0)); }
After executing the code above, your employees.csv
file should have two new lines at the end:
Robert Smith, 30, Sales Assistant Kate Court, 26, Receptionist Steve Roberts, 32, Driver Marta,32,Assistant Jessica,35,Actor
Writing objects into a CSV file in java is similar to adding a plain string. The only difference is that you should convert the object to a string before passing the object for writing. To continue with the same example, I will create a class Person
and add a new method to write Person object to the file. See this in action below:
private static class Person{ String name; int age; String jobTitle; Person(String name, int age, String jobTitle){ this.name = name; this.age = age; this.jobTitle = jobTitle; } String toCsv(){ return name + "," + age + "," + jobTitle; } }
public void writeObjectsToCSVFile(String path, Person... persons) throws IOException { Path filePath = Paths.get(path); try(BufferedWriter buffer = Files.newBufferedWriter(filePath, Charset.defaultCharset(), StandardOpenOption.APPEND)){ buffer.newLine(); for(Person person:persons){ buffer.append(person.toCsv()); buffer.newLine(); } } }
And here is some code that will call the code above:
public static void main(String[] args) throws IOException { new CSVFileHelper().writeObjectsToCSVFile("employees.csv", new Person("Marta",32,"Assistant"), new Person( "Jessica",35,"Actor")); List<String> lines = new CSVFileHelper().readLinesFromCSVFile("employees.csv"); System.out.println(lines.get(0)); }
After running this code, just as before, the code added two new lines with the employee information into the CSV file.
Check out the source code here.
To summarise, in this article, you have learned how to read and write data into a CSV file. This task is relatively easy to achieve using BufferedReader
and BufferedWriter
, enabling read or write access to the file.
Maven Jar Plugin – How to make an executable jar file
Automate Data Entry – How to Create a Selenium bot
Creating a Speech Recognition Program with Python & Google API
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java