First time with Apache Commons CSV

Source: Internet
Author: User
Tags iterable

1. New Java project csvexample in Eclipse.

2. Add a CSV file:
Create a new CSV file under the "\CSVEXAMPLE\SRC" directory, or copy the CSV file elsewhere to this directory.

The contents are as follows:

3. Download the source and extract the Apache Commons CSV:
https://commons.apache.org/proper/commons-csv/download_csv.cgi
Binaries or source, whichever is OK. I've got two of them.

4. Add the Org.apache.commons.csv package to the project (two ways):
First Type:
Copy the Org directory under the "\commons-csv-1.4-src\src\main\java" directory to the SRC directory of the Csvexample project and refresh the Csvexample project. You can see a org.apache.commons.csv package below the directory.

The second type:
Introduction of third party libraries
Open eclipse–> Item Right-click –> build path–> Add External archives–> Select Jar file

5. Create a new Csvdemo package, write code in this package, and practice using Apache. Read CSV

Package Csvdemo;

Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException;
Import Java.io.Reader;

Import Org.apache.commons.csv.CSVFormat;
Import Org.apache.commons.csv.CSVRecord;

public class Csvreader {public

    static void Main (string[] args) {
        try {
            Reader in=new filereader ("c:\\users\\ TianLin liao\\workspace\\csvexample\\src\\foods.csv ");
            Iterable<csvrecord> Records=csvformat.excel.withheader (). Parse (in);
            for (Csvrecord record:records) {
                System.out.print (record.get ("Name") + "");
                System.out.print (Record.get ("Favorite Color") + "");
                System.out.println (Record.get ("Favorite Food"));
            }
        catch (FileNotFoundException e) {
            e.printstacktrace ();
        } catch (IOException e) {
            e.printstacktrace (); c20/>}}}

if there is no header:
public class Csvreader {public

    static void Main (string[] args) {
        try {
            Reader in=new filereader ("c:\\users\\ TianLin liao\\workspace\\csvexample\\src\\foods.csv ");
            Iterable<csvrecord> Records=csvformat.excel.parse (in);
            for (Csvrecord record:records) {
                System.out.print (record.get (0) + "");
                System.out.print (Record.get (1) + "");
                System.out.println (Record.get (2));
            }
        catch (FileNotFoundException e) {
            e.printstacktrace ();
        } catch (IOException e) {
            e.printstacktrace (); c13/>}}}


Write CSV:
Package Csvdemo;
Import Java.io.FileWriter;
Import java.util.ArrayList;

Import java.util.List;
Import Org.apache.commons.csv.CSVFormat;

Import Org.apache.commons.csv.CSVPrinter; public class Csvwriter {public static void main (string[] args) {final string[] file_header={"ID", "Name", "Sc
        Ore "};

        Final String file_name= "Student.csv";
        Create student Objects Student student1=new Student ("7601", "Abby", 113);
        Student student2=new Student ("7301", "Sam", 121);
        Student student3=new Student ("7101", "Yuuki", 130);
        Student student4=new Student ("7302", "Jay", 100);
        Student student5=new Student ("7500", "Zoe", 98);
        Add to a List list<student> students = new arraylist<> ();
        Students.add (STUDENT1);
        Students.add (Student2);
        Students.add (STUDENT3);
        Students.add (STUDENT4);

        Students.add (STUDENT5);
        FileWriter Filewriter=null;
        Csvprinter Csvprinter=null; CsvformAt Csvformat=csvformat.default.withheader (File_header);
            try {filewriter=new fileWriter (file_name);

            Csvprinter=new Csvprinter (FileWriter, Csvformat);
                for (Student student:students) {list<string> record=new arraylist<> ();
                Record.add (Student.getid ());
                Record.add (Student.getname ());
                Record.add (String.valueof (Student.getscore ()));
            Csvprinter.printrecord (record);
        } catch (Exception e) {e.printstacktrace ();
                }finally {try{filewriter.flush ();
                Filewriter.close ();
            Csvprinter.close ();
            }catch (Exception e) {e.printstacktrace ();
    Class student{private String ID;
    private String name;

    private int score;
        Public Student (string ID, string name, int score) {super (); This.id = ID;
        THIS.name = name;
    This.score = score;
    Public String GetId () {return id;
    public void SetId (String id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    public int Getscore () {return score;
    The public void SetScore (int score) {This.score = score; }

}

After writing, the effect is as follows:

In the code to read CSV, change the file path to "Student.csv" to read the just-written CSV.

Reader in=new FileReader ("Student.csv");

reference materials
https://examples.javacodegeeks.com/core-java/apache/commons/csv-commons/ writeread-csv-files-with-apache-commons-csv-example/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.