Java解析CSV文件

1、CSV文件是什么


csv(Comma Separate Values)文件即逗号分隔符文件,它是一种文本文件,可以直接以文本打开,以逗号分隔。windows默认用excel打开。它的格式包括以下几点(它的格式最好就看excel是如何解析的。):

①每条记录占一行;
②以逗号为分隔符;
③逗号前后的空格会被忽略;
④字段中包含有逗号,该字段必须用双引号括起来;
⑤字段中包含有换行符,该字段必须用双引号括起来;
⑥字段前后包含有空格,该字段必须用双引号括起来;
⑦字段中的双引号用两个双引号表示;
⑧字段中如果有双引号,该字段必须用双引号括起来;
⑨第一条记录,可以是字段名;

2、读取CSV文件

若记录中不包含换行符,可直接用BufferedReader来按行来读取。类似如下:
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
	        String line = null;
	        while ((line = bufferedReader.readLine()) != null) {
	            String[] columns = line.split("\",\"");
	           /* if(columns[0].length() != 14){
	            	//System.out.print(columns[0].length());
	                continue;
	            }*/
}


若记录中包含换行符,则不能再用上述方式,可以使用 Ostermiller Java Utilities
jar包下载地址:http://ostermiller.org/utils/download.html
示例代码:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.Ostermiller.util.ExcelCSVParser;
import com.Ostermiller.util.LabeledCSVParser;

public class CsvFileParser{   
  
    private static LabeledCSVParser csvParser;//csvParser   
  
    private int currLineNum = -1;//The current line number for reading.   
  
    private String[] currLine = null;//The data of current line.  
 
  
    public CsvFileParser(InputStream in) throws IOException {  
          
            csvParser = new LabeledCSVParser(new ExcelCSVParser(in));  
            currLineNum = csvParser.getLastLineNumber();  
    }  
    
    
    public String[] readLine() throws IOException {  
        currLine = csvParser.getLine();   
  
        currLineNum = csvParser.getLastLineNumber();   
  
        return currLine;  
    }  
      
     
        
        
    public static void main(String args[]) throws Exception{
    	String filePath = "D:\\Pronto_Statistics_2016_03_25_04_07_44.csv";
    	FileInputStream in=new FileInputStream(filePath);
    	CsvFileParser csvReader=new CsvFileParser(in);
    	boolean flag = true;
    	while(flag){
	    	String[] str = csvReader.readLine();
	    	if(str!=null){
	    		for(int i = 0; i<str.length;i++){
		    		System.out.print(str[i]);
		    	}
		    	System.out.println();
	    	}else{
	    		flag=false;
	    	}
	    	
    	}
    	csvParser.close(); 
    	
    }
  
}   

详细源码可见:

CSVLexer.lex Source Code :http://ostermiller.org/utils/src/CSVLexer.lex.html

CSVParse.java Source Code:http://ostermiller.org/utils/src/CSVParse.java.html




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值