我以前做的一个项目中用Java解析csv文件 主要是把csv的行列转换 是以逗号分割的 我开始想用数组搞定 可是每一行的长度不一样 就没弄好 后来用的下面的代码 可是有个地方弄的不是很好。下面的代码可改成更好的或者 谁有更好的办法 给点指教 谢谢
package test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVAnalysis {
private InputStreamReader fr = null;
private BufferedReader br = null;
public CSVAnalysis(String f) throws IOException {
fr = new InputStreamReader(new FileInputStream(f));
}
/**
* 读取csv文件按照行读取成字符串,把字符串存入数组
* @return
* @throws IOException
*/
public List<List<String>> readCSVFile() throws IOException {
br = new BufferedReader(fr);
String rec = null;// 一行
List<List<String>> listFile = new ArrayList<List<String>>();
try {
//读取字符串,按照要求存入数组
int j = 0;//控制列
//int num = br.readLine().split(",").length ;//读取长度
int Lnum = 19;这里我想换成自动读取的行列
int num = 2002;
String Test[][] = new String[num][Lnum];
while ((rec = br.readLine()) != null) {
int i = 0;//控制行
int b = rec.indexOf(",");
while (b != -1) {
String s1 = rec.substring(b + 1);
String s2 = rec.substring(0, b);
Test[j] = s2;
rec = s1;
i++;
b = rec.indexOf(",");
}
if (!rec.equals(null)) {
Test[j] = rec;
}
j++;
}
//写入csv中
FileWriter fw = new FileWriter("d:\\Test5.csv", true);
for (int i1 = 0; i1 < num; i1++) {
for (int j1 = 0; j1 < 19; j1++) {
if (j1 < 18) {
fw.write(Test[i1][j1] + ",");
} else {
fw.write(Test[i1][j1]);
}
}
fw.write("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
}
return listFile;
}
public static void main(String[] args) throws Throwable {
CSVAnalysis parser = new CSVAnalysis("d:/Test_20130312_test.csv");
parser.readCSVFile();
}
}
|
|