You tin charge information from a CSV file inwards Java programme yesteryear using BufferedReader degree from java.io package. You tin read the file business yesteryear line as well as convert each business into an object representing that data. Actually in that place are span of ways to read or parse CSV file inwards Java e.g. y'all tin purpose a 3rd political party library similar Apache common CSV or y'all tin purpose Scanner class, but inwards this instance nosotros volition purpose traditional agency of loading CSV file using BufferedReader.
Here are the steps to charge information from CSV file inwards Java without using whatever 3rd political party library :
And hither is our sample CSV file which contains details of my favorite books. It's called books.csv, each row stand upward for a mass alongside title, toll as well as writer information. First column is championship of book, 2nd column is toll as well as 3rd column is writer of the book.
Reading the File
To read the CSV file nosotros are going to purpose a BufferedReader inwards combination alongside a FileReader. FileReader is used to read a text file inwards platform's default graphic symbol encoding, if your file is encoded inwards other graphic symbol encoding hence y'all should purpose InputStreamReader instead of FileReader class. We volition read ane business at a fourth dimension from the file using readLine() method until the EOF (end of file) is reached, inwards that instance readLine() volition provide a null.
Split comma separated String
We own got the string that nosotros read from CSV file as well as separate it upward using the comma equally the 'delimiter' (because its a CSV file). This creates an array alongside the all the columns of CSV file equally nosotros want, all the same values are silent inwards Strings, hence nosotros ask to convert them into proper type e.g. prices into float type equally discussed inwards my postal service how to convert String to float inwards Java. Once nosotros got all the attribute values, nosotros exercise an object of Book degree yesteryear invoking constructor of mass equally new Book() as well as locomote yesteryear all those attributes. Once nosotros Book object hence nosotros but add together them to our ArrayList.
If y'all similar this tutorial as well as interested to larn to a greater extent than near how to bargain alongside files as well as directory inwards Java, y'all tin checkout next Java IO tutorial :
Here are the steps to charge information from CSV file inwards Java without using whatever 3rd political party library :
- Open CSV file using FileReader object
- Create BufferedReader from FileReader
- Read file business yesteryear business using readLine() method
- Split each business on comma to acquire an array of attributes using String.split() method
- Create object of Book degree from String array using novel Book()
- Add those object into ArrayList using add() method
- Return the List of books to caller
And hither is our sample CSV file which contains details of my favorite books. It's called books.csv, each row stand upward for a mass alongside title, toll as well as writer information. First column is championship of book, 2nd column is toll as well as 3rd column is writer of the book.
Effective Java,42,Joshua Bloch
Head First Java,39,Kathy Sierra
Head First Design Pattern,44,Kathy Sierra
Introduction to Algorithm,72,Thomas Cormen
Step yesteryear Step guide to charge a CSV file inwards Java
Let's acquire through each steps to discovery out what they are doing as well as how they are doing :Reading the File
To read the CSV file nosotros are going to purpose a BufferedReader inwards combination alongside a FileReader. FileReader is used to read a text file inwards platform's default graphic symbol encoding, if your file is encoded inwards other graphic symbol encoding hence y'all should purpose InputStreamReader instead of FileReader class. We volition read ane business at a fourth dimension from the file using readLine() method until the EOF (end of file) is reached, inwards that instance readLine() volition provide a null.
Split comma separated String
We own got the string that nosotros read from CSV file as well as separate it upward using the comma equally the 'delimiter' (because its a CSV file). This creates an array alongside the all the columns of CSV file equally nosotros want, all the same values are silent inwards Strings, hence nosotros ask to convert them into proper type e.g. prices into float type equally discussed inwards my postal service how to convert String to float inwards Java. Once nosotros got all the attribute values, nosotros exercise an object of Book degree yesteryear invoking constructor of mass equally new Book() as well as locomote yesteryear all those attributes. Once nosotros Book object hence nosotros but add together them to our ArrayList.
Java Program to charge information from CSV file
Here is our amount programme to read a CSV file inwards Java using BufferedReader. It's proficient instance of how to read information from file business yesteryear line, separate string using a delimiter as well as how to exercise object from a String array inwards Java. Once y'all charge information into programme y'all tin insert into database, or y'all tin persist into another format or y'all tin ship it over network to other 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 java.util.ArrayList; import java.util.List; /** * Simple Java programme to read CSV file inwards Java. In this programme nosotros volition read * listing of books stored inwards CSV file equally comma separated values. * * @author WINDOWS 8 * */ public class CSVReaderInJava { public static void main(String... args) { List<Book> books = readBooksFromCSV("books.txt"); // let's impress all the soul read from CSV file for (Book b : books) { System.out.println(b); } } private static List<Book> readBooksFromCSV(String fileName) { List<Book> books = new ArrayList<>(); Path pathToFile = Paths.get(fileName); // exercise an instance of BufferedReader // using attempt alongside resource, Java seven characteristic to closed resources try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) { // read the start business from the text file String business = br.readLine(); // loop until all lines are read while (line != null) { // purpose string.split to charge a string array alongside the values from // each business of // the file, using a comma equally the delimiter String[] attributes = line.split(","); Book mass = createBook(attributes); // adding mass into ArrayList books.add(book); // read adjacent business earlier looping // if destination of file reached, business would last null business = br.readLine(); } } catch (IOException ioe) { ioe.printStackTrace(); } return books; } private static Book createBook(String[] metadata) { String mention = metadata[0]; int toll = Integer.parseInt(metadata[1]); String writer = metadata[2]; // exercise as well as provide mass of this metadata return new Book(name, price, author); } } class Book { private String name; private int price; private String author; public Book(String name, int price, String author) { this.name = name; this.price = price; this.author = author; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book [name=" + mention + ", price=" + toll + ", author=" + writer + "]"; } } Output Book [name=Effective Java, price=42, author=Joshua Bloch] Book [name=Head First Java, price=39, author=Kathy Sierra] Book [name=Head First Design Pattern, price=44, author=Kathy Sierra] Book [name=Introduction to Algorithm, price=72, author=Thomas Cormen]
That's all near how to charge CSV file inwards Java without using whatever 3rd political party library. You own got learned how to purpose BufferedReader to read information from CSV file as well as hence how to separate comma separated String into String array yesteryear using String.split() method. Though y'all tin exercise it fifty-fifty to a greater extent than easily yesteryear using 3rd political party library similar Apache common CSV, but knowing how to exercise it using pure Java volition help y'all to larn telephone commutation classes cast JDK.
If y'all similar this tutorial as well as interested to larn to a greater extent than near how to bargain alongside files as well as directory inwards Java, y'all tin checkout next Java IO tutorial :
- How to read Excel File inwards Java using Apache POI? [example]
- How to append information into an existing file inwards Java? [example]
- 2 ways to read a file inwards Java? [tutorial]
- How to exercise a file or directory inwards Java? [example]
- How to read a text file using Scanner degree inwards Java? [answer]
- How to write content into file using BufferedWriter degree inwards Java? [example]
- How to read username as well as password from ascendance business inwards Java? [example]
- How to read Date as well as String from Excel file inwards Java? [tutorial]
0 Response to "How to charge information from CSV file inwards Java - Example"
Posting Komentar