OpenCSV处理csv的java工具

本文介绍了OpenCSV库在处理CSV文件时的多种功能,包括处理每行的任意数量值,忽略引用元素中的逗号,处理跨越多行的引用条目,自定义分隔符和引用字符,以及一次性读取所有条目或使用迭代器模型。同时,还展示了如何从String数组创建自动转义嵌入引用字符的CSV文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What is opencsv?
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.
Where can I get it?
Source and binaries are available from   Sourceforge. You can check out the   javadocs  online.
What features does opencsv support?
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)



How do I read and parse a CSV file?
If you want to use an Iterator style pattern, you might do something like this:
    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();
           
which will give you a   List  of   String[]  that you can iterate over. If all else fails, check out the   Javadoc.
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:
    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:
    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:
    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:
     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.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:
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/.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值