?? csv.java
字號:
import java.util.regex.*;
import java.util.*;
import java.io.*;
public class CSVParser
{
public CSVParser()
{
}
private StringBuffer buf = null;
public ArrayList parse() {
String str;
ArrayList rows = new ArrayList();
Pattern pRows = Pattern.compile("(([^\n\"]*(\"[^\"]*(\"{2})*[^\"]*\"[^\n\"]*)*))\n");
Pattern pCells = Pattern.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
Matcher mRows = pRows.matcher(buf);
System.out.println("\n\n-----------rows------------------");
while(mRows.find()) {
System.out.println("{" + mRows.group(1) + "}");
Matcher mCells = pCells.matcher(mRows.group(1) + ",");
ArrayList cells = new ArrayList();
while(mCells.find()) {
str = mCells.group();
str = str.replaceAll("(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");
str = str.replaceAll("(?sm)(\"(\"))", "$2");
cells.add(str);
}
rows.add(cells);
}
return rows;
}
public void readCSVFile(File CSVFile) {
int chr;
buf = new StringBuffer("");
try {
BufferedReader in = new BufferedReader(new FileReader(CSVFile));
while((chr=in.read()) != -1) {
buf.append((char)chr);
}
in.close();
System.out.println("-------------csv file content--------------");
System.out.print(buf);
} catch (FileNotFoundException fnfex) {
fnfex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
public static void main(String[] args) throws Throwable {
File file = new File("C:\\address.csv");
CSVParser parser = new CSVParser();
parser.readCSVFile(file);
ArrayList rows = parser.parse();
int size = rows.size();
System.out.println("\n\n--------------parsed result------------------");
System.out.println("---------row size = " + size);
for (int i = 0; i < size; i++) {
System.out.println("--rows[" + i + "] = " + rows.get(i));
ArrayList cells = (ArrayList)(rows.get(i));
System.out.println("--cell size = " + cells.size());
for(int j = 0; j < cells.size(); j ++) {
System.out.println("cells["+ i + "," + j + "] = " + cells.get(j));
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -