我有派| 分隔的csv文件。我想用Java读取此文件。我有一个Java代码,可读取Java中逗号分隔的文件,但在 分离的csv文件
我的文件包含“客户代码|产品代码|发送到银行|发送到分支”这种类型的数据不是逗号分隔的。
Java代码
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class TestPieCSVtoXLs {
public static void main(String[] args) {
String csvFile = "D:\\VijayTest\\csvFile.csv";
DataInputStream myInput;
String thisLine;
ArrayList<ArrayList<String>> arList = new ArrayList<ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = null;
try {
FileInputStream fis = new FileInputStream(csvFile);
myInput = new DataInputStream(fis);
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList<String>();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
System.out.println(strar[j]);
al.add(strar[j]);
}
}
arList.add(al);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
你应该改变
String strar[] = thisLine.split(",");
到
String strar[] = thisLine.split("\\|");
由于|
是正则表达式中的元字符,因此您需要对其进行转义。同样如评论中所述,此解决方案未考虑特殊情况...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句