您的位置:首页 > 编程语言 > Java开发

java解析CSV文件

2012-02-16 16:58 435 查看
package util;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class CSVReader {

private File cvsFile;

public CSVReader() {

}

public CSVReader(File cvsFile, File logFile) {

this.cvsFile = cvsFile;

}

public File getCvsFile() {

return cvsFile;

}

public void setcvsFile(File cvsFile) {

this.cvsFile = cvsFile;

}

public void load(Loader loader) {

try {

// 读取CVS文件

BufferedReader reader = new BufferedReader(new FileReader(this.cvsFile));

// 逐行读取,并导入数据到数据库

String line = null;

// 行号

int rownum = 1;

while ((line = reader.readLine()) != null) {

try {

loader.load(parseLine(line));

} catch(Exception e) {

}

// 行号加一

rownum ++;

}

} catch (FileNotFoundException e) {} catch (IOException e) {}

}

private static List<String> parseLine(String line) {

// 解析字符串

List<String> tokenList = new ArrayList<String>();

StringBuffer token = new StringBuffer();

// 是否在引号内

boolean inQuotation = false;

for (int i = 0; i < line.length(); i++) {

char c = line.charAt(i);

if (c == ',' && !inQuotation) {

tokenList.add(token.toString());

token.setLength(0);

} else if (c == '"') {

if (inQuotation) {

char d = line.charAt(i+1);

if (d == '"') {

token.append(c);

i ++;

} else {

inQuotation = !inQuotation;

}

} else {

inQuotation = !inQuotation;

}

} else {

token.append(c);

}

}

tokenList.add(token.toString());

// 返回解析结果

return tokenList;

}

public static void main(String[] args) throws Exception {

CSVReader.readCSV("D:/TestFile1.csv");

File cvsFile = new File("D:/TestFile1.csv");

File logFile = new File("D:/Load.log");

CSVReader loader = new CSVReader(cvsFile, logFile);

loader.load(new Loader(){

public void load(List recFieldList) throws Exception{

for (int i = 0; i < recFieldList.size(); i++) {

System.out.println("F[" + i + "]=" + recFieldList.get(i).toString().replaceAll("'", ""));

}

}

});

}

public static List<String[]> readCSV(String filepath) throws IOException {

//filepath ="D:/TestFile1.csv"

File file = new File(filepath);//到目录下取文件

BufferedReader br = null;

List<String[]> list = new ArrayList<String[]>();

try {

br = new BufferedReader(new InputStreamReader(

new FileInputStream(file)));//获得文件流

String line = null;

while ((line = br.readLine()) != null) {//读取一行

list.add(line.replaceAll("'","").split(","));

}

} finally {

if (br != null) {

br.close();

}

}

return list;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: