How to Read From Csv in Java

Disclosure: This commodity may contain affiliate links. When y'all buy, nosotros may earn a commission.

How to load data from CSV file in Java - Instance

Yous can load data from a CSV file in a Java program by using BufferedReader grade from thejava.io package. You can read the file line by line and convert each line into an object representing that data. Really, there are a couple of means to read or parse CSV files in Coffee east.g. y'all can use a third-party library similar Apache eatables CSV or you can use Scanner class, but in this case, we volition use the traditional way of loading CSV files using BufferedReader.

Here are the steps to load data from CSV file in Java without using any 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 get an array of attributes using Cord.split up() method
  • Create an object of Book course from String array using new Volume()
  • Add together those object into ArrayList using add together() method
  • Return the List of books to the caller

And here is our sample CSV file which contains details of my favorite books. It's chosen books.csv , each row represents a book with the title, cost, and writer information. The outset cavalcade is the title of the volume, the 2nd column is the price, and the third column is the author of the book.

Effective Java,42,Joshua Bloch
Head Get-go Coffee,39,Kathy Sierra
Head Start Design Pattern,44,Kathy Sierra
Introduction to Algorithm,72,Thomas Cormen

Step past Stride guide to load a CSV file in Java

Let's go through each step to find out what they are doing and how they are doing :

1. Reading the File

To read the CSV file we are going to use a BufferedReader in combination with a FileReader. FileReader is used to read a text file in the platform's default character encoding, if your file is encoded in other grapheme encodings then you should use InputStreamReader instead of FileReader class. We will read one line at a time from the file using readLine() method until the EOF (end of file) is reached, in that case,readLine() volition return a goose egg.

2. Split up comma separated String

We take the string that nosotros read from the CSV file and divide information technology upwardly using the comma as the 'delimiter' (considering information technology'south a CSV file). This creates an array with all the columns of the CSV file equally nosotros desire, notwithstanding, values are even so in Strings, and so nosotros need to catechumen them into proper type due east.g. prices into float blazon as discussed in my post how to convert Cord to float in Coffee.

Once we got all the attribute values, nosotros create an object of the Book class by invoking the constructor of the book as anew Book() and laissez passer all those attributes. Once we Volume objects then we only add together them to our ArrayList.

How to load CSV file in Java using BufferedReader

Java Plan to load data from CSV file

Here is our full program to read a CSV file in Java using BufferedReader. Information technology'south a practiced example of how to read data from a file line past line, split string using a delimiter, and how to create objects from a String array in Java. In one case y'all load data into the plan you can insert it into a database, or you can persist into some other format or you lot tin transport it over the network to some other JVM.

                import                coffee.io.BufferedReader;                import                java.io.IOException;                import                java.nio.charset.StandardCharsets;                import                coffee.nio.file.Files;                import                java.nio.file.Path;                import                java.nio.file.Paths;                import                java.util.ArrayList;                import                java.util.List;                /**  * Elementary Java program to read CSV file in Coffee. In this programme we will read  * list of books stored in CSV file as comma separated values.  *   *                  @author                  WINDOWS 8  *  */                public                course                CSVReaderInJava                {                public                static                void                main(String... args) {                List<Book>                books                =                readBooksFromCSV("books.txt");                // allow's print all the person read from CSV file                for                (Book                b                :                books) {                Organisation                .out.println(b);         }     }                private                static                List<Book>                readBooksFromCSV(String                fileName) {                List<Book>                books                =                new                ArrayList<>();                Path                pathToFile                =                Paths                .go(fileName);                // create an instance of BufferedReader                // using endeavor with resource, Coffee 7 feature to shut resource                effort                (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) {                // employ cord.split to load a string array with the values from                // each line of                // the file, using a comma as the delimiter                String[] attributes                =                line.divide(",");                Volume                volume                =                createBook(attributes);                // adding book into ArrayList                books.add(book);                // read side by side line before looping                // if end of file reached, line would exist nix                line                =                br.readLine();             }          }                catch                (IOException                ioe) {             ioe.printStackTrace();         }                return                books;     }                private                static                Book                createBook(String[] metadata) {                Cord                proper name                =                metadata[0];                int                cost                =                Integer                .parseInt(metadata[1]);                String                author                =                metadata[two];                // create and return volume of this metadata                return                new                Book(name, price, author);     }  }                class                Book                {                private                String                name;                private                int                price;                private                String                author;                public                Volume(String                name,                int                price,                Cord                author) {         this.name                =                name;         this.cost                =                price;         this.author                =                writer;     }                public                String                getName() {                return                name;     }                public                void                setName(String                proper noun) {         this.name                =                name;     }                public                int                getPrice() {                return                price;     }                public                void                setPrice(int                cost) {         this.price                =                price;     }                public                String                getAuthor() {                render                author;     }                public                void                setAuthor(String                author) {         this.author                =                author;     }                @Override                public                Cord                toString() {                return                "Book [proper name="                +                proper name                +                ", price="                +                price                +                ", author="                +                author                +                "]";     }  }                Output                Book                [name=                Effective                Java, price=                42, author=                Joshua                Bloch]                Volume                [name=                Caput                First                Java, price=                39, author=                Kathy                Sierra]                Book                [proper noun=                Head                First                Design                Blueprint, toll=                44, author=                Kathy                Sierra]                Book                [name=                Introduction                to                Algorithm, toll=                72, author=                Thomas                Cormen]

That'due south all about how to load CSV files in Java without using any third-political party library.  You have learned how to apply BufferedReader to read data from CSV files and and then how to divide comma-separated String into String array by using the String.split() method.

If you lot like this tutorial and interested to learn more than about how to deal with files and directories in Java, you lot tin can check out the following Java IO tutorial :

  • How to read Excel Files in Coffee using Apache POI? [example]
  • How to suspend data into an existing file in Java? [example]
  • two means to read a file in Coffee? [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 password from the command line in Java? [instance]
  • How to read Engagement and String from Excel file in Java? [tutorial]

Though you read CSV files in Java even more than easily by using a third-party library like Apache commons CSV, knowing how to do information technology using pure Java will help you to larn key classes from JDK.

davissatedilly.blogspot.com

Source: https://www.java67.com/2015/08/how-to-load-data-from-csv-file-in-java.html

0 Response to "How to Read From Csv in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel