Java Read From File and Parse Files.lines

Disclosure: This commodity may contain affiliate links. When you purchase, we may earn a committee.

How to load information from CSV file in Java - Example

You tin can load information from a CSV file in a Java programme by using BufferedReader class from thejava.io package. You tin read the file line by line and convert each line into an object representing that information. Really, in that location are a couple of ways to read or parse CSV files in Java e.thou. you lot can utilize a third-political party library similar Apache commons CSV or you can use Scanner class, but in this example, nosotros volition use the traditional style 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 past line using readLine() method
  • Split each line on comma to go an array of attributes using String.split() method
  • Create an object of Volume class from String array using new Book()
  • Add those object into ArrayList using add() method
  • Return the List of books to the caller

And hither is our sample CSV file which contains details of my favorite books. It's called books.csv , each row represents a book with the title, price, and author information. The showtime cavalcade is the championship of the book, the 2nd cavalcade is the price, and the tertiary column is the author of the book.

Constructive Coffee,42,Joshua Bloch
Head Kickoff Java,39,Kathy Sierra
Caput First Design Pattern,44,Kathy Sierra
Introduction to Algorithm,72,Thomas Cormen

Pace by Step guide to load a CSV file in Java

Permit's go through each step to observe 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'south default graphic symbol encoding, if your file is encoded in other character encodings then you should use InputStreamReader instead of FileReader class. Nosotros 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() will return a zippo.

ii. Carve up comma separated String

We take the string that we read from the CSV file and split it upward using the comma as the 'delimiter' (considering it's a CSV file). This creates an array with all the columns of the CSV file as we desire, even so, values are still in Strings, so we need to catechumen them into proper blazon e.1000. prices into float type as discussed in my post how to convert String to bladder in Coffee.

Once we got all the attribute values, we create an object of the Volume class past invoking the constructor of the volume as anew Book() and laissez passer all those attributes. One time we Book objects then we simply add them to our ArrayList.

How to load CSV file in Java using BufferedReader

Java Program to load data from CSV file

Here is our total program to read a CSV file in Coffee using BufferedReader. It's a good case of how to read data from a file line past line, split cord using a delimiter, and how to create objects from a String assortment in Java. Once you load information into the program you tin can insert it into a database, or you can persist into some other format or you tin can send it over the network to another JVM.

                import                java.io.BufferedReader;                import                coffee.io.IOException;                import                coffee.nio.charset.StandardCharsets;                import                java.nio.file.Files;                import                coffee.nio.file.Path;                import                java.nio.file.Paths;                import                java.util.ArrayList;                import                java.util.List;                /**  * Simple Java program to read CSV file in Java. In this program nosotros will read  * list of books stored in CSV file as comma separated values.  *   *                  @author                  WINDOWS eight  *  */                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(String                fileName) {                List<Book>                books                =                new                ArrayList<>();                Path                pathToFile                =                Paths                .get(fileName);                // create an case of BufferedReader                // using try with resource, Java vii feature to close resources                endeavour                (BufferedReader                br                =                Files                .newBufferedReader(pathToFile,                StandardCharsets                                  .US_ASCII)) {                // read the first line from the text file                Cord                line                =                br.readLine();                // loop until all lines are read                while                (line                !=                null) {                // utilise string.split to load a cord array with the values from                // each line of                // the file, using a comma as the delimiter                String[] attributes                =                line.split(",");                Book                volume                =                createBook(attributes);                // calculation book into ArrayList                books.add(book);                // read next line before looping                // if end of file reached, line would be null                line                =                br.readLine();             }          }                grab                (IOException                ioe) {             ioe.printStackTrace();         }                return                books;     }                private                static                Book                createBook(Cord[] metadata) {                String                proper name                =                metadata[0];                int                price                =                Integer                .parseInt(metadata[1]);                String                author                =                metadata[2];                // create and render volume of this metadata                render                new                Book(name, cost, author);     }  }                form                Book                {                individual                Cord                proper noun;                individual                int                toll;                private                Cord                author;                public                Book(String                name,                int                price,                String                author) {         this.proper noun                =                proper name;         this.cost                =                price;         this.author                =                author;     }                public                Cord                getName() {                return                proper noun;     }                public                void                setName(Cord                name) {         this.name                =                name;     }                public                int                getPrice() {                return                price;     }                public                void                setPrice(int                price) {         this.price                =                price;     }                public                Cord                getAuthor() {                return                author;     }                public                void                setAuthor(String                author) {         this.author                =                author;     }                @Override                public                String                toString() {                return                "Book [name="                +                proper name                +                ", price="                +                price                +                ", author="                +                author                +                "]";     }  }                Output                Book                [proper name=                Constructive                Java, toll=                42, author=                Joshua                Bloch]                Volume                [proper name=                Head                First                Java, price=                39, author=                Kathy                Sierra]                Book                [name=                Head                Outset                Design                Pattern, price=                44, writer=                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-political party library.  You have learned how to employ BufferedReader to read information from CSV files and then how to split up comma-separated String into String array by using the String.split() method.

If y'all similar this tutorial and interested to learn more almost how to deal with files and directories in Java, y'all can check out the post-obit Java IO tutorial :

  • How to read Excel Files in Coffee using Apache POI? [case]
  • How to suspend data into an existing file in Java? [example]
  • 2 means to read a file in Java? [tutorial]
  • How to create a file or directory in Coffee? [example]
  • How to read a text file using the Scanner class in Coffee? [answer]
  • How to write content into a file using BufferedWriter form in Java? [case]
  • How to read username and password from the command line in Java? [example]
  • How to read Date and Cord from Excel file in Coffee? [tutorial]

Though you read CSV files in Java even more than easily by using a tertiary-party library like Apache commons CSV, knowing how to exercise it using pure Java will aid you lot to acquire central classes from JDK.

jorgensentherser.blogspot.com

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

0 Response to "Java Read From File and Parse Files.lines"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel