Skip to content Skip to sidebar Skip to footer

How to Read Csv File in Javain Python

CSV stands for Comma-Separated Values. It is a certificate blueprint utilized to keep data in an accounting page or dataset in a straightforward text structure. A delimiter is used to recognize and isolate information in comma-separated values.

Introduction

The CSV record design moves structured information betwixt programs that locally piece of work on incongruent organizations.

Prerequisites

To follow along, the reader should:

  • Have a bones knowledge of Coffee.
  • Have an IDE of your choice installed. I'll be using Eclipse IDE.

Table of contents

  • Introduction
  • Prerequisites
  • Table of contents
  • Creating a CSV file
    • Microsoft Excel office
    • Notepad
  • Java String.carve up() technique
  • Java scanner class
  • Using openCSV API
    • Important OpenCSV classes
  • Reading CSV files in Coffee
  • Conclusion

Creating a CSV file

Microsoft Excel office

  • Offset, open up the Excel office on your computer.
  • Second, open up a blank workbook. Then feed the information beneath into the Excel certificate.

microsoft-excel-csv

  • Salve the excel file as CSV (comma delimited). Name the certificate as comma-separated, and finish saving it.

excelsave

Notepad

  • Let's go started by opening Notepad.
  • 2nd, feed in the information as displayed below. Remember to separate each information with a comma.
            Student Name,Faculty,Registration No,Fees Residual,Campus Stanley Kuria,Education,37916808,3150,Main Davidson Kanyua,Computing,38094044,8500,Meru Tess Wambui,Engineering,21666504,13500,Nairobi Esther Njoroge,Health,37809504,5500,Nakuru                      
  • So save the file as commaseperated.csv. The file nosotros created should look like the one beneath.

notepadcsv

Coffee Cord.split() technique

Cord.dissever, applied to interruption string around matches of the given standard articulation. In the code below, we imported BufferedReader. BufferedReader reads the file line by line to the stop.

                          import              coffee.io.FileReader;              import              java.io.IOException;              //signals an exception of some kind has occurred                                          import              java.io.BufferedReader;              //Reads text from a grapheme-input stream                                          course              readcsv              {              public              static              void              principal              (String[]              args)              {              Cord sample              =              ","              ;              String mystring;              effort              {              BufferedReader brdrd              =              new              BufferedReader(              new              FileReader(              "C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv"              ));              while              ((mystring              =              brdrd.              readLine              ())              !=              cipher              )              //Reads a line of text                                          {              Cord[]              student              =              mystring.              split up              (sample);              //utilized to dissever the string                                          System.              out              .              println              (              "Proper noun: "              +              student[0]              +              ",Faculty: "              +              student[1]              +              ", Registration No: "              +              pupil[2]              +              ", Fees Balance: "              +              student[three]              +              ", Campus:  "              +              student[4]              +              ""              );              }              }              catch              (IOException e)              //catches exception in the try block                                          {              e.              printStackTrace              ();              //Prints this throwable and its backtrace                                          }              }              }                      

The output of the lawmaking is as shown below:

            Proper noun: Student Proper name,Faculty: Faculty, Registration: Registration No, Fees Balance: Fees Remainder, Campus:  Campus Name: Stanley Kuria,Faculty: Education, Registration: 37916808, Fees Rest: 3150, Campus:  Main Name: Davidson Kanyua,Faculty: Calculating, Registration: 38094044, Fees Remainder: 8500, Campus:  Meru Proper noun: Tess Wambui,Faculty: Applied science, Registration: 21666504, Fees Rest: 13500, Campus:  Nairobi Name: Esther Njoroge,Kinesthesia: Health, Registration: 37809504, Fees Balance: 5500, Campus:  Nakuru                      

Coffee scanner class

This is a class in the Java.util bundle, used to get input from the user. It breaks information into tokens, utilizing the delimiter pattern. It is the almost straightforward method to read input in Java lawmaking.

We used the scanner grade to read CSV files in Java in the code below:

                          import              coffee.util.Scanner;              //contains scanner class                                          import              coffee.io.*;              grade              mycsvread              {              public              static              void              primary              (String[]              args)              throws              FileNotFoundException              //This exception will be thrown when a file with the specified pathname does not exist                                          {              Scanner myscanner              =              new              Scanner(              new              File(              "C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv"              ));              //Creates a new File                                          myscanner.              useDelimiter              (              ", "              );              //Sets the delimiter                                          while              (myscanner.              hasNext              ())              //Returns a boolean(truthful) if this scanner has another token in its input                                          {              System.              out              .              println              (myscanner.              next              ());              //adjacent complete scanner is returned hither                                          }              myscanner.              close              ();              //myscanner is closed                                          }              }                      

The output is every bit shown below:

            Student Name,Faculty,Registration No,Fees Balance,Campus Stanley Kuria,Education,37916808,3150,Main Davidson Kanyua,Computing,38094044,8500,Meru Tess Wambui,Engineering,21666504,13500,Nairobi Esther Njoroge,Health,37809504,5500,Nakuru                      

Using openCSV API

OpenCSV is an outsider API utilized to peruse different adaptations of the comma-separated document. It supports all basic Comma-separated operations. OpenCSV is used since Java does not provide native back up to read Comma-Separated values.

Important OpenCSV classes

  • CSVWrite - enables writing data into a CSV file.
  • CSVToBean - utilized to populate Java Awarding with CSV data.
  • BeanToCSV - applied to export data from JavaBean to Comma-seperated value file.

Comma-separated values are read in two ways, mainly:

  • By line: In this example, the comma-separated values are consecutively read from one line to another.
  • All data: utilizes readAll() technique to peruse all records at once.

Instance: List allData = csvReader.readAll();

The syntax for open CSV: public CSVReader(Reader reader, char separator)

Reading CSV files in Java

Step 1

Create 2 folders in eclipse-workspace and name them CSVDoc and CSVdocuments. In the CSVdocuments folder, move the CSV files that you volition use. In this case, we will use comma-separated and semicolon-separated files.

Then in the CSVDoc folder paste opencsv-5.five.2 and commons-lang3-3.1 jar files. If you don't have them, download them past clicking opencsv5.5.2 and commonlangs3-3.1

csvdoc

Step two

Open Eclipse, and create a Coffee project. Name the project every bit CSVOperation and click next.

createproject

Pace 3

Click Libraries and select Classpath. Then select add external Jars and add jars from CSVDoc in the Eclipse-workspace folder. Then click finish.

libraries

jars

externaljars

Step 4

After that, create a Coffee class. Right-click on the project CSVOperation and select new, then select course.

class

Stride 5

Proper name the class as ReadCSVExample and click finish.

nameclass

Footstep six

Then copy the code sample below and paste. Run the plan.

                          import              com.opencsv.CSVReader;              //external library                                          import              java.io.FileReader;              //Reads text from character files using a default buffer size                                          public              class              ReadCSVExample              {              private              static              String LOCATION_OF_THE_FILE=              "C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv"              ;              //file location                                          public              static              void              principal              (Cord[]              args)              {              LineByLine(LOCATION_OF_THE_FILE);              }              public              static              void              LineByLine              (Cord myfile)              {              try              {              FileReader freader=              new              FileReader(myfile);              //created an object of freader class                                          @SuppressWarnings              (              "resources"              )              CSVReader creader=              new              CSVReader(freader);              // created creader object by parsing freader as a parameter                                          String              []              nextRecord;              // created an array of type Cord                                          //read data line past line                                          while              ((nextRecord              =              creader.              readNext              ())!=              null              )              {              for              (String token:              nextRecord)              System.              out              .              println              (token              +              "\t"              );              //will bring the value of cell seperated by tab space                                          }              System.              out              .              println              ();              }              take hold of              (Exception eastward)              //to take hold of any exception inside try block                                          {              e.              printStackTrace              ();              //used to print a throwable class along with other dataset class                                          }              }              }                      

The output should resemble the one beneath:

            Student Name Kinesthesia Registration No Fees Residual Campus Stanley Kuria Education              37916808              3150              Main Davidson Kanyua Computing              38094044              8500              Meru Tess Wambui Engineering              21666504              13500              Nairobi Esther Njoroge Health              37809504              5500              Nakuru                      

You will note the absenteeism of commas. This is considering when using open up CSV API, the commas are ignored.

Permit's implement a programme to read a CSV file not separated by commas. Instead, information technology'due south separated with semi-colons(;).

The CSV file that we are going to read is shown below:

semi-colon-seperated

Copy the program below and paste and run it.

                          import              com.opencsv.CSVReader;              //external library                                          import              coffee.io.FileReader;              //Reads text from character files using a default buffer size                                          public              class              ReadCSVExample              {              private              static              String LOCATION_OF_THE_FILE=              "C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\semicolonseperated.csv"              ;              //file location                                          public              static              void              main              (Cord[]              args)              {              LineByLine(LOCATION_OF_THE_FILE);              }              public              static              void              LineByLine              (Cord myfile)              {              attempt              {              FileReader freader=              new              FileReader(myfile);              //created an object of freader form                                          @SuppressWarnings              (              "resources"              )              CSVReader creader=              new              CSVReader(freader);              // created creader object by parsing freader equally a parameter                                          String              []              nextRecord;              // created an array of type String                                          //read data line by line                                          while              ((nextRecord              =              creader.              readNext              ())!=              null              )              {              for              (String token:              nextRecord)              Organization.              out              .              println              (token              +              "\t"              );              //volition bring the value of cell seperated by tab space                                          }              System.              out              .              println              ();              }              grab              (Exception e)              //to grab any exception inside try cake                                          {              e.              printStackTrace              ();              //used to print a throwable class along with other dataset class                                          }              }              }                      

The output is shown below:

            Educatee Name;Faculty;Registration No;Fees Residue;Campus Stanley Kuria;Instruction;37916808;3150;Main Davidson Kanyua;Computing;38094044;8500;Meru Tess Wambui;Engineering;21666504;13500;Nairobi Esther Njoroge;Health;37809504;5500;Nakuru                      

In the output above, you will notation the presence of semi-colon separators. This is because OpenCSV ignores commas, merely other separators are recognized.

Determination

This article focused on various techniques to create CSV files in Java. Nosotros also learned different methods of reading Comma Separated Values (CSV) in Coffee. Finally, nosotros used open up CSV API to read CSV files.

Happy coding!


Peer Review Contributions by: Odhiambo Paul

rogersherus1950.blogspot.com

Source: https://www.section.io/engineering-education/working-with-csv-files-in-java/

Post a Comment for "How to Read Csv File in Javain Python"