opencsv open source CSV file operations package Introduction

2010-04-13  来源:本站原创  分类:Java  人气:681 

opencsv is a very simple csv (comma-separated values) parser library for Java. It was developed because all of current csv parsers I've come across don't have commercial-friendly licenses.


opencsv supports all the basic csv-type things you're likely to want to do:

* Arbitrary numbers of values per line
* Ignoring commas in quoted elements
* Handling quoted entries with embedded carriage returns (ie entries that span multiple lines)
* Configurable separator and quote characters (or use sensible defaults)
* Read all the entries at once, or use an Iterator style model
* Creating csv files from String [] (ie. automatic escaping of embedded quote chars)

If you want to use an Iterator style pattern, you might do something like this:

Java code

  1. CSVReader reader = new CSVReader (new FileReader ("yourfile.csv"));
  2. String [] nextLine;
  3. while ((nextLine = reader.readNext ())! = null) (
  4. / / NextLine [] is an array of values from the line
  5. System.out.println (nextLine [0] + nextLine [1] + "etc ...");
  6. )
  7. Or, if you might just want to slurp the whole lot into a List, just call readAll ()...
  8. CSVReader reader = new CSVReader (new FileReader ("yourfile.csv"));
  9. List myEntries = reader.readAll ();

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        // nextLine[] is an array of values from the line
        System.out.println(nextLine[0] + nextLine[1] + "etc...");
    }

Or, if you might just want to slurp the whole lot into a List, just call readAll()...

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    List myEntries = reader.readAll();


Can I use my own separators and quote characters?

Yes. There are constructors that cater for supplying your own separator and quote characters. Say you're using a tab for your separator, you can do something like this:

Java code

  1. CSVReader reader = new CSVReader (new FileReader ("yourfile.csv"), '\ t');

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t');

And if you single quoted your escaped characters rather than double quote them, you can use the three arg constructor:

Java code

  1. CSVReader reader = new CSVReader (new FileReader ("yourfile.csv"), '\ t', '\'');

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t', '\'');

You may also skip the first few lines of the file if you know that the content doesn't start till later in the file. So, for example, you can skip the first two lines by doing:

Java code

  1. CSVReader reader = new CSVReader (new FileReader ("yourfile.csv"), '\ t', '\'', 2);

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t', '\'', 2);

Can I write csv files with opencsv?

Yes. There is a CSVWriter in the same package that follows the same semantics as the CSVReader. For example, to write a tab separated file:

Java code

  1. CSVWriter writer = new CSVWriter (new FileWriter ("yourfile.csv"), '\ t');
  2. / / Feed in your array (or convert your data to an array)
  3. String [] entries = "first # second # third". Split ("#");
  4. writer.writeNext (entries);
  5. writer.close ();

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
     // feed in your array (or convert your data to an array)
     String[] entries = "first#second#third".split("#");
     writer.writeNext(entries);
        writer.close();

If you'd prefer to use your own quote characters, you may use the three arg version of the constructor, which takes a quote character (or feel free to pass in CSVWriter.NO_QUOTE_CHARACTER).

You can also customise the line terminators used in the generated file (which is handy when you're exporting from your Linux web application to Windows clients). There is a constructor argument for this purpose.

Can I dump out SQL tables to CSV?

Yes you can. Sean Sullivan added a neat feature to CSVWriter so you can pass writeAll () a ResultSet.

Java code

  1. java.sql.ResultSet myResultSet = ....
  2. writer.writeAll (myResultSet, includeHeaders);

java.sql.ResultSet myResultSet = ....
      writer.writeAll(myResultSet, includeHeaders);

Is there a way to bind my CSV file to a list of Javabeans?

Yes there is. Kyle Miller added a new set of classes to allow you to bind a CSV file to a list of JavaBeans based on column name, column position, or a custom mapping strategy. You can find the new classes in the au.com . bytecode.opencsv.bean package. Here's how you can map to a java bean based on the field positions in your CSV file:

Java code

  1. ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy ();
  2. strat.setType (YourOrderBean.class);
  3. String [] columns = new String [] ("name", "orderNumber", "id"); / / the fields to bind do in your JavaBean
  4. strat.setColumnMapping (columns);
  5. CsvToBean csv = new CsvToBean ();
  6. List list = csv.parse (strat, yourReader);

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
      strat.setType(YourOrderBean.class);
      String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
      strat.setColumnMapping(columns);

      CsvToBean csv = new CsvToBean();
      List list = csv.parse(strat, yourReader);

For more detailed examples, check out the test cases for each of the available mapping strategies under the / test / au / com / bytecode / opencsv / bean /.

Can I use opencsv in my commercial applications?

Yes. Opencsv is available under a commercial-friendly Apache 2.0 license. You are free to include it in your commericial applications without any fee or charge, and you are free to modify it to suit your circumstances. To find out more details of the license , read the Apache 2.0 license agreement.
Can I get the source? More example code?

Yes. The download from the SourceForge page includes the full source in the / src directory. It's one file, so go crazy. There is also a sample addressbook csv reader in the / examples directory. And for extra marks, there's a JUnit test suite in the / test directory.

相关文章
  • opencsv open source CSV file operations package Introduction 2010-04-13

    opencsv is a very simple csv (comma-separated values) parser library for Java. It was developed because all of current csv parsers I've come across don't have commercial-friendly licenses. opencsv supports all the basic csv-type things you're likely

  • java programming source code file operations thought IO5 2010-05-05

    package com.dirlist; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedInputFile { // Buffered input file public static String read(String filename) throws IOException{ //BufferedReader From ch

  • java programming source code file operations thought IO6 2010-05-05

    package com.dirlist; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; public class FileOutputShortcut { /** * The shortcut text file output */ static String file="FileOutputShortcut.o

  • java programming source code file operations thought IO8 2010-05-06

    Explore channels and buffers package com.dirlist; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.io.*; public class ChannelCopy { private static final int BSIZE=1024; public static void main(String[] args) throws IOExce

  • java programming source code file operations thought IO10 2010-05-08

    package com.dirlist; import java.nio.*; public class IntBufferDemo { /** * View buffer, use view buffer encapsulates the byte buffer */ private static final int BSIZE=1024; public static void main(String[] args) { ByteBuffer bb=ByteBuffer.allocate(BS

  • [Csvjdbc] Java parsing csv file and change the open source package 2010-06-17

    Before doing a small desktop program, because of the need to read csv file ("," separated) in the data, found a csvjdbc this open source package: http://sourceforge.net/projects/csvjdbc/ csvjdbc simple point is that the csv in the table of conte

  • 3) Linux Programming Introduction - File Operations 2010-09-26

    Files under Linux operating Introduction: In this section we will discuss the various file operations under linux function. File creation and read-write Each attribute Directory file operation Pipe File -----------------------------------------------

  • opencsv java import csv and xls files summary 2010-04-13

    If the binary file into csv or xls file format needed jxl.jar package to resolve, If the file is comma delimited csv format text file is needed opencsv.jar package to resolve. How to distinguish a binary file format, a simple way to use Notepad to op

  • [Change] linux file directory structure Introduction 2010-05-14

    Of: Cai Xiao Jianbo off: Xiaomao imaginings Overall, the poor classification / Media to mount usb storage devices, DVD, CD-ROM, etc. / Mnt for temporary mounting file systems, removable devices should be mounted to / media up / Home user than root di

  • [J2ME] file operations 2010-12-05

    [J2ME] file operations for a 1. JSR75 methods Jsr75 in two parts, one File, the local file system, in part, PIM, is like the phone book information, I will learn is the File section, through the import javax.microedition.io.file .* in the package, al

  • JAVA write file operations Gadgets 2010-12-13

    Long time no written code, very, very strange, a lot of things are forgotten, wrote a small tool that small problem there, get me a whole night, and later that knows the problem, but it still is in view of solving complex, thought did not need a gadg

  • Java file operations enhancement tools 2010-03-29

    Java file operations enhancement tools -------------------------------------------------- ------------------------------ 2008-12-15 18:30:43 Tags: File IO commons [pushed to the technical ring] Copyright Statement: original works, and if reproduced,

  • Java SE 7 file operations (1)-Path Class Description 2010-03-24

    Taken from the developers of the Sky 1. Path of the concept of <br /> file system files will be organized and stored in medium, usually one or more of the hard disk. Currently, most of the file system tree is a way to store documents. In the top of

  • Export CSV file using Java reflection to export Excel alternative 2010-03-28

    package com.resoft.prophet.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter;

  • New features of Java SE 7 file operations (9) - traverse the directory tree 2010-04-13

    Transferred from the developer's sky In some cases, we may need to traverse the entire directory tree, such as the need to find all. Java file. Java SE 7 provides a very convenient way to achieve this kind of functionality. Implementation of Java SE

  • Maple wind ASP class file operations (FSO) (change) 2010-05-04

    '============================================================= ' Author : Maple leaves were 'QQ:455948725 'E-mail:[email protected] 'WebSite:http://www.fengyekun.com '============================================================= class FsoClass privat

  • Windows API for file operations 2010-08-02

    The following is provided in the document windows to operate the API functions and features: Windows API function function CloseHandle to close a kernel object. Including documents, maps, processes, threads, security, and synchronization objects. Inv

  • file operations android development 2010-12-16

    Android have permission to file operations: Determine whether the inserted SD card Environment.getExternalStorageState (). Equals ( android.os.Environment.MEDIA_MOUNTED); Access to sd card root directory File skRoot = Environment.getExternalStorageDi

  • java file operations to read and write basic 2011-01-11

    package com.hzsuwang.java; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java

  • examples of file operations android 2011-05-15

    Lesson, android file operation instance, mainly SDcard read and write operations. package com.myclover.file.service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import an