问题描述
我试图读取一个文件,其中每一行都有用逗号分隔的数据成员,这些数据成员用于填充对象的数据成员,我尝试使用正则表达式“ |”用于将“,”和“ \ n”以及“ \ r”分开的符号,以转到新行。但是,在读取第一行之后,不会立即读取第二行的第一个数据成员,而是事先读取了一个“”字符。我使用了错误的正则表达式符号吗?还是我没有使用正确的方法?我读到有很多方法可以解决此问题,并选择使用扫描器,因为这似乎是最简单的,使用缓冲区读取器似乎非常令人困惑,因为它似乎返回数组,而不是我要获取的单个字符串和整数。
CSV文件看起来像这样
stringA,stringB,stringC,1,2,3
stringD,stringE,stringF,4,5,6
stringG,stringH,stringI,7,8,9
我的代码看起来像这样
//In list class
public void load() throws FileNotFoundException
{
Scanner input = new Scanner(new FileReader("a_file.csv"));
object to_add; //To be added to the list
input.useDelimiter(",|\\n|\\r");
while (input.hasNext())
{
String n = input.next(); //After the first loop run,this data gets the value ""
String l = input.next(); //During this second run,this member gets the data that n was supposed to get,"stringD"
String d = input.next(); //This one gets "stringE"
int a = input.nextInt(); //And this one tries to get "stringF",which makes it crash
int c = input.nextInt();
to_add = new object(n,l,d,a,b,c); //Calling copy constructor to populate data members
insert(to_add); //Inserting object to the list
}
input.close();
}
解决方法
使用Apache Commons CSV。这是用户指南https://commons.apache.org/proper/commons-csv/user-guide.html
,您可以使用OpenCSV进行此操作,这是tutorial的使用方法。您可以从Maven Repository下载该库。
下面是您需要做的代码
Reader reader = Files.newBufferedReader(Paths.get("path/to/csvfile.csv"));
CSVReader csvReader = new CSVReader(reader);
List<String[]> dataList = new ArrayList<>();
dataList = csvReader.readAll();
reader.close();
csvReader.close();
Object to_add;
for (String[] rowData : dataList) {
String textOne = rowData[0];
String textTwo = rowData[1];
String textThree = rowData[2];
int numberOne = Integer.parseInt(rowData[3]);
int numberTwo = Integer.parseInt(rowData[4]);
int numberThree = Integer.parseInt(rowData[5]);
to_add = new Object(textOne,textTwo,textThree,numberOne,numberTwo,numberThree);
insert(to_add);
}