Java How to Read a Csv File Into an Array
Disclosure: This article may incorporate chapter links. When yous buy, we may earn a commission.
How to load data from CSV file in Java - Instance
You can load data from a CSV file in a Java program by using BufferedReader course from thejava.io package. Y'all can read the file line past line and convert each line into an object representing that data. Actually, there are a couple of ways to read or parse CSV files in Java east.g. y'all tin can use a third-party library similar Apache commons CSV or you can apply Scanner class, but in this example, we volition apply the traditional way of loading CSV files using BufferedReader.
Hither are the steps to load data from CSV file in Java without using whatever third-party library :
- Open CSV file using FileReader object
- Create BufferedReader from FileReader
- Read file line by line using readLine() method
- Split each line on comma to go an array of attributes using String.split() method
- Create an object of Volume grade from String array using new Volume()
- Add together those object into ArrayList using add() method
- Render the List of books to the caller
And here is our sample CSV file which contains details of my favorite books. Information technology'due south called books.csv , each row represents a book with the title, price, and writer information. The start cavalcade is the title of the book, the second column is the price, and the third cavalcade is the author of the book.
Constructive Java,42,Joshua Bloch
Head First Coffee,39,Kathy Sierra
Head First Design Pattern,44,Kathy Sierra
Introduction to Algorithm,72,Thomas Cormen
Step by Stride guide to load a CSV file in Java
Allow'south go through each step to detect out what they are doing and how they are doing :
ane. Reading the File
To read the CSV file nosotros are going to apply a BufferedReader in combination with a FileReader. FileReader is used to read a text file in the platform'southward default grapheme encoding, if your file is encoded in other character encodings then you should use InputStreamReader instead of FileReader class. We will read 1 line at a fourth dimension from the file using readLine() method until the EOF (end of file) is reached, in that case,readLine() will return a zippo.
2. Split comma separated String
We take the string that we read from the CSV file and separate it upwards using the comma equally the 'delimiter' (because it's a CSV file). This creates an array with all the columns of the CSV file as we desire, nonetheless, values are even so in Strings, then nosotros demand to convert them into proper type e.g. prices into float type as discussed in my post how to convert String to bladder in Java.
In one case we got all the attribute values, we create an object of the Book class by invoking the constructor of the book as anew Book() and pass all those attributes. Once we Book objects then nosotros only add together them to our ArrayList.
Coffee Program to load data from CSV file
Hither is our full plan to read a CSV file in Java using BufferedReader. Information technology'due south a expert example of how to read data from a file line by line, carve up string using a delimiter, and how to create objects from a String array in Coffee. Once you load data into the program you tin can insert information technology into a database, or you tin can persist into some other format or you tin send it over the network to another JVM.
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import coffee.util.ArrayList; import java.util.List; /** * Uncomplicated Coffee program to read CSV file in Coffee. In this program we will read * list of books stored in CSV file every bit comma separated values. * * @writer WINDOWS 8 * */ public class CSVReaderInJava { public static void main(String... args) { List<Volume> books = readBooksFromCSV("books.txt"); // let's print all the person read from CSV file for (Book b : books) { System .out.println(b); } } private static List<Book> readBooksFromCSV(Cord fileName) { List<Book> books = new ArrayList<>(); Path pathToFile = Paths .get(fileName); // create an example of BufferedReader // using try with resource, Java 7 feature to shut resources try (BufferedReader br = Files .newBufferedReader(pathToFile, StandardCharsets .US_ASCII)) { // read the first line from the text file String line = br.readLine(); // loop until all lines are read while (line != null) { // utilize string.split to load a string array with the values from // each line of // the file, using a comma as the delimiter String[] attributes = line.split(","); Book book = createBook(attributes); // adding book into ArrayList books.add(book); // read adjacent line before looping // if cease of file reached, line would be aught line = br.readLine(); } } catch (IOException ioe) { ioe.printStackTrace(); } return books; } private static Book createBook(String[] metadata) { String name = metadata[0]; int cost = Integer .parseInt(metadata[1]); String writer = metadata[2]; // create and return book of this metadata return new Book(name, price, writer); } } class Book { private String name; private int price; private String writer; public Book(String name, int price, Cord author) { this.name = proper noun; this.price = price; this.writer = author; } public String getName() { render name; } public void setName(String name) { this.name = proper name; } public int getPrice() { render price; } public void setPrice(int price) { this.price = cost; } public String getAuthor() { render author; } public void setAuthor(Cord author) { this.writer = writer; } @Override public String toString() { return "Book [proper noun=" + proper noun + ", price=" + price + ", author=" + author + "]"; } } Output Book [name= Effective Coffee, cost= 42, author= Joshua Bloch] Book [proper noun= Head Get-go Java, toll= 39, author= Kathy Sierra] Book [proper noun= Head First Design Pattern, price= 44, author= Kathy Sierra] Book [name= Introduction to Algorithm, price= 72, author= Thomas Cormen]
That's all about how to load CSV files in Java without using any third-party library. Yous have learned how to use BufferedReader to read information from CSV files and then how to dissever comma-separated String into String assortment by using the String.split() method.
If you like this tutorial and interested to larn more virtually how to deal with files and directories in Java, you lot can check out the following Java IO tutorial :
- How to read Excel Files in Coffee using Apache POI? [example]
- How to suspend information into an existing file in Coffee? [example]
- two ways to read a file in Java? [tutorial]
- How to create a file or directory in Java? [example]
- How to read a text file using the Scanner class in Java? [answer]
- How to write content into a file using BufferedWriter class in Java? [example]
- How to read username and countersign from the control line in Java? [example]
- How to read Appointment and String from Excel file in Java? [tutorial]
Though you read CSV files in Java fifty-fifty more hands by using a third-political party library like Apache commons CSV, knowing how to do information technology using pure Java will help you lot to acquire key classes from JDK.
Source: https://www.java67.com/2015/08/how-to-load-data-from-csv-file-in-java.html
0 Response to "Java How to Read a Csv File Into an Array"
Post a Comment