Java Read CSV File In Java With OpenCSV library and File garbled solution, M

Source: Internet
Author: User



Sample.csv file:

COUNTRY,CAPITAL,POPULATIONIndia,New Delhi, 1.21BPeople's republic of China,Beijing, 1.34BUnited States,Washington D.C., 0.31B



1. Use readNext () to read CSV files in a row and return a String Array

package com.jiangge.csv.opencsvtest;import java.io.FileReader;import java.io.IOException;import au.com.bytecode.opencsv.CSVReader;//COUNTRY,CAPITAL,POPULATION//India,New Delhi, 1.21B//People's republic of China,Beijing, 1.34B//United States,Washington D.C., 0.31B/** * use readNext() method of CSVReader class to read CSV file line by line.  * It returns a String array for each value in row. */public class ReadLineByLine {public static void main(String[] args) throws IOException {String csvFilename = "C:\\sample.csv";CSVReader csvReader = new CSVReader(new FileReader(csvFilename));String[] row = null;while((row = csvReader.readNext()) != null) {    System.out.println(row[0] + " # " + row[1] + " #  " + row[2]);}//...csvReader.close();}}

Output result:

COUNTRY # CAPITAL #  POPULATIONIndia # New Delhi #   1.21BPeople's republic of China # Beijing #   1.34BUnited States # Washington D.C. #   0.31B



2. Read the entire CSV file at a time using the readAll () method and return the List

package com.jiangge.csv.opencsvtest;import java.io.FileReader;import java.io.IOException;import java.util.List;import au.com.bytecode.opencsv.CSVReader;//COUNTRY,CAPITAL,POPULATION//India,New Delhi, 1.21B//People's republic of China,Beijing, 1.34B//United States,Washington D.C., 0.31B/** * read full CSV file once. The readAll() method of CSVReader class comes handy for this. * The readAll() method returns a List of String[] for given CSV file. * @author jiangge */public class ReadAllTest {public static void main(String[] args) throws IOException {String[] row = null;String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename));List content = csvReader.readAll(); for (Object object : content) {    row = (String[]) object;    System.out.println(row[0] + " # " + row[1]+ " #  " + row[2]);}//...csvReader.close();}}



Output result:

COUNTRY # CAPITAL #  POPULATIONIndia # New Delhi #   1.21BPeople's republic of China # Beijing #   1.34BUnited States # Washington D.C. #   0.31B




3. Use other separator numbers and skip some rows. For more information, see here: Click to open the link.

CSVReader reader = new CSVReader (new FileReader (file ),';')
CSVReader reader = new CSVReader (new FileReader (file ),'#')


Skip the first five rows, starting from the first 6th rows:

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'', 5);


Iv. Mapping CSV with Java beans

1. java bean

package com.jiangge.csv.opencsvtest;public class Country {private String countryName;private String capital;private String population;public String getPopulation() {return population;}public void setPopulation(String population) {this.population = population;}public String getCountryName() {return countryName;}public void setCountryName(String countryName) {this.countryName = countryName;}public String getCapital() {return capital;}public void setCapital(String capital) {this.capital = capital;}}


2. Associate JavaBean, Now we can map this bean with Opencsv and read the CSV file

Package com.jiangge.csv. opencsvtest; import java. io. dataInputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. inputStreamReader; import java. util. list; import au.com. bytecode. opencsv. CSVReader; import au.com. bytecode. opencsv. bean. columnPositionMappingStrategy; import au.com. bytecode. opencsv. bean. csvToBean; // COUNTRY, CAPITAL, POPULATION // India, New Delhi, 1.21B // People's republic of China, Beijing, 1.34B // United States, Washington D. C ., 0.31B/*** map this bean (Country. java) with Opencsv and read the CSV file. check out below example: * @ author jiangge */public class JavaBeanMapWithCSV {public static void main (String [] args) throws FileNotFoundException {ColumnPositionMappingStrategy strategy = new partition (); strategy. setType (Country. class); // associate the JavaBeanString [] columns = new String [] {"countryName", "capital"}; // the fields to bind do in your JavaBean, the class variable attribute strategy in JavaBean. setColumnMapping (columns); CsvToBean csv = new CsvToBean (); String csvFilename = "C :\\ sample.csv"; CSVReader csvReader = new CSVReader (new FileReader (csvFilename )); // DataInputStream in = new DataInputStream (new FileInputStream (new File (csvFilename); // csvReader = new CSVReader (new InputStreamReader (in, "UTF-8 "),',', '\ '', 1); // The contents commented out by the two lines can solve the Chinese garbled problem List list = csv. parse (strategy, csvReader); for (Object object: list) {Country country = (Country) object; System. out. println (country. getCapital ());}}}

Output result:

CAPITALNew DelhiBeijingWashington D.C.



OpenCSV library Chinese garbled solution:

DataInputStream in = new DataInputStream (new FileInputStream (new File (csvFilename); csvReader = new CSVReader (new InputStreamReader (in, "UTF-8 "),',', '\ '', 1); // The contents commented out by the two lines can solve the Chinese Garbled text problem.


References:

Http://viralpatel.net/blogs/java-read-write-csv-file/







Related Article

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.