opencsv开源 CSV文件操作包简介

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 代码
  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.               
  8.   
  9. Or, if  you might just want to slurp the whole lot into a List, just call readAll()...  
  10.   
  11.     CSVReader reader = new  CSVReader( new  FileReader( "yourfile.csv" ));  
  12.     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 代码
  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 代码
  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 代码
  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 代码
  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 代码
  1. java.sql.ResultSet myResultSet = ....  
  2. writer.writeAll(myResultSet, includeHeaders);  
  3.         
      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 代码
  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.   
  6. CsvToBean csv = new  CsvToBean();  
  7. List list = csv.parse(strat, yourReader);  
  8.         
      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.

你可能感兴趣的:(apache,sql,bean,linux,IE)