How to Read a Csv File in Another Class Java

Disclosure: This commodity may contain affiliate links. When you purchase, nosotros may earn a commission.

How to load data from CSV file in Java - Instance

You lot can load information from a CSV file in a Java program by using BufferedReader form from thecoffee.io package. You can read the file line past line and convert each line into an object representing that data. Really, at that place are a couple of ways to read or parse CSV files in Coffee e.g. you can use a 3rd-party library like Apache commons CSV or you can use Scanner class, but in this example, we will employ the traditional way of loading CSV files using BufferedReader.

Here are the steps to load information 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 become an array of attributes using String.split() method
  • Create an object of Volume class from String assortment using new Book()
  • Add those object into ArrayList using add together() method
  • Render the List of books to the caller

And here is our sample CSV file which contains details of my favorite books. It'southward called books.csv , each row represents a volume with the title, price, and author data. The first column is the title of the volume, the second column is the price, and the third column is the author of the volume.

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

Step past Step guide to load a CSV file in Coffee

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

i. Reading the File

To read the CSV file nosotros are going to utilise 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 character encodings and so y'all should utilize InputStreamReader instead of FileReader form. We will read one line at a fourth dimension from the file using readLine() method until the EOF (terminate of file) is reached, in that case,readLine() will render a naught.

two. Split comma separated String

We take the cord that nosotros read from the CSV file and split it upwards using the comma as the 'delimiter' (considering it's a CSV file). This creates an array with all the columns of the CSV file equally nosotros want, however, values are yet in Strings, so we need to convert them into proper type e.thou. prices into float type equally discussed in my mail how to convert String to float in Java.

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

How to load CSV file in Java using BufferedReader

Coffee Program to load information from CSV file

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

                import                coffee.io.BufferedReader;                import                coffee.io.IOException;                import                java.nio.charset.StandardCharsets;                import                coffee.nio.file.Files;                import                java.nio.file.Path;                import                java.nio.file.Paths;                import                coffee.util.ArrayList;                import                java.util.List;                /**  * Simple Java programme to read CSV file in Java. In this program we will read  * listing of books stored in CSV file equally comma separated values.  *   *                  @author                  WINDOWS viii  *  */                public                grade                CSVReaderInJava                {                public                static                void                main(String... args) {                List<Book>                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                .become(fileName);                // create an instance of BufferedReader                // using try with resource, Java seven feature to close resources                effort                (BufferedReader                br                =                Files                .newBufferedReader(pathToFile,                StandardCharsets                                  .US_ASCII)) {                // read the start line from the text file                String                line                =                br.readLine();                // loop until all lines are read                while                (line                !=                zilch) {                // use string.split up to load a cord assortment with the values from                // each line of                // the file, using a comma as the delimiter                String[] attributes                =                line.split(",");                Volume                book                =                createBook(attributes);                // adding volume into ArrayList                books.add(volume);                // read next line before looping                // if end of file reached, line would exist null                line                =                br.readLine();             }          }                catch                (IOException                ioe) {             ioe.printStackTrace();         }                return                books;     }                individual                static                Volume                createBook(String[] metadata) {                String                name                =                metadata[0];                int                price                =                Integer                .parseInt(metadata[one]);                Cord                author                =                metadata[2];                // create and return book of this metadata                return                new                Book(name, price, writer);     }  }                form                Book                {                individual                Cord                name;                individual                int                cost;                individual                Cord                writer;                public                Volume(String                proper noun,                int                price,                Cord                writer) {         this.name                =                proper noun;         this.cost                =                price;         this.author                =                writer;     }                public                String                getName() {                return                name;     }                public                void                setName(Cord                proper name) {         this.proper name                =                proper name;     }                public                int                getPrice() {                return                toll;     }                public                void                setPrice(int                cost) {         this.price                =                cost;     }                public                String                getAuthor() {                return                author;     }                public                void                setAuthor(String                writer) {         this.author                =                author;     }                @Override                public                String                toString() {                return                "Book [name="                +                proper noun                +                ", price="                +                price                +                ", author="                +                author                +                "]";     }  }                Output                Book                [proper noun=                Constructive                Java, price=                42, author=                Joshua                Bloch]                Book                [proper noun=                Head                First                Java, price=                39, author=                Kathy                Sierra]                Book                [name=                Head                Kickoff                Design                Pattern, price=                44, author=                Kathy                Sierra]                Book                [name=                Introduction                to                Algorithm, price=                72, author=                Thomas                Cormen]

That's all most how to load CSV files in Java without using whatever third-political party library.  You take learned how to apply BufferedReader to read data from CSV files and and then how to split up comma-separated Cord into String array by using the Cord.split() method.

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

  • How to read Excel Files in Java using Apache POI? [example]
  • How to append information into an existing file in Coffee? [example]
  • ii ways 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? [example]
  • How to read Appointment and String from Excel file in Coffee? [tutorial]

Though you read CSV files in Java even more easily by using a third-political party library like Apache commons CSV, knowing how to practise it using pure Coffee will help y'all to learn key classes from JDK.

taylorfece1936.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 a Csv File in Another Class Java"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel