用户名:
密 码: 记住密码
当前位置 : 主页>程序设计>Java技术>列表

使用java将csv文件分割

来源:互联网 时间:2008-02-23

csv即用逗号分割的文件,本类实现的结果与Excel打开csv时基本相同

不同的是Excel对于回车也作为一个项目的内容,而在这里是以行为单位进行分割

aa,bb,cc,dd ----->|aa|bb|cc|dd 即分割为aa,bb,cc,dd四个元素

"aa","bb","cc","dd" ----->|aa|bb|cc|dd

"a""a","a""""b" -------->|a"a|a""b

"a"b","c""d"e",f""e ------->|ab"|c"de"|f""e|

//Generated by fason

package fason;

import Java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;

public class CSVParse {
public static ArrayList parseCSV(String lineStr){
ArrayList colList = new ArrayList();
StringBuffer sb = new StringBuffer(lineStr);
int colFlg = 0;
boolean comaFlg = false;
StringBuffer colBuf = new StringBuffer();
while(sb.length()>0){
char c = sb.charAt(0);
if(comaFlg == false){
if(c == ','){
colList.add(colBuf.toString());
colBuf = new StringBuffer();
}else if(c == '\"'){
colFlg = 1;
char tmpc = '\0';
if(sb.length()>1){
tmpc = sb.charAt(1);
}
if(tmpc == '\"'){
colFlg = 2;
sb.deleteCharAt(1);
}
comaFlg = true;
}else{
colFlg = 2;
colBuf.append(c);
comaFlg = true;
}
}else{
if(colFlg == 2 && c == ','){
colList.add(colBuf.toString());
colBuf = new StringBuffer();
comaFlg =false;
}else if(colFlg ==1 && c == '\"'){
char tmpc = '\0';
if(sb.length()>1){
tmpc = sb.charAt(1);
}
if(tmpc == '\"'){
colBuf.append(tmpc);
sb.deleteCharAt(1);
}else{
colFlg = 2;
}
}else{
colBuf.append(c);
}
}
sb.deleteCharAt(0);
}
colList.add(colBuf.toString());
return colList;
}
public static ArrayList parseCSVFile(String filePath){
BufferedReader br;
try{
br = new BufferedReader(new FileReader(filePath));
}catch(Exception e){
System.out.print(e.getMessage());
return null;
}
ArrayList lineList = new ArrayList();
try{
String s;
while((s = br.readLine()) != null){
lineList.add(s);
}
}catch(Exception e){
System.out.print(e.getMessage());
}
ArrayList lineColList = new ArrayList();
Iterator ite = lineList.iterator();
while(ite.hasNext()){
String lineStr = (String)ite.next();
lineColList.add(parseCSV(lineStr));
}
return lineColList;
}
}

上一篇: Spring Framework 1.1.5 has just been released
下一篇: servlet彩色验证码

版权申明:本站文章均来自网络,如有侵权,请联系028-86262244-215 ,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。

 热点关注
  • 官方网址: west263.com 西部数码.cn
  • CopyRight © 2002~2011 西部数码 版权所有
  • 电话总机:028-86263960 (50线)      传真:028-86264041
  • 400电话: 400-667-9006