我有派分离的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");
}
}发布于 2015-05-19 07:15:38
你应该换衣服
String strar[] = thisLine.split(",");至
String strar[] = thisLine.split("\\|");因为|是正则表达式中的元字符,所以需要转义它。此外,正如评论中所述,这个解决方案没有考虑到特殊情况.
发布于 2015-05-19 07:22:41
OpenCSV是一个很好的库,可以在java中与CSV交互时使您的生活变得轻松。
发布于 2015-05-19 09:00:13
在java中读取csv文件的代码
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");
}https://stackoverflow.com/questions/30318864
复制相似问题