使用java将csv文件分割

类别:Java 点击:0 评论:0 推荐:

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;
 }
}

本文地址:http://com.8s8s.com/it/it11118.htm