这是我的代码。我从两个CSV文件中读取数据(一个用于用户,一个用于餐馆),我在Selenium Webdriver中提供两个不同的测试类,带有两个不同的数组,以便对测试进行参数化。
有没有办法在这里重复这么多代码?
final String FILE_PATH = "src/test/resources/250.csv";
final String FILE_PATH2 = "src/test/resources/places.csv";
//read CSV file and supply data for test purposes
CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) { // 5 is the number of columns
list.add(nextLine[i]);
}
array.add(list);
}
reader.close();
CSVReader reader2 = new CSVReader(new FileReader(FILE_PATH2));
ArrayList<ArrayList<String>> array2 = new ArrayList<ArrayList<String>>();
String[] nextLine2;
while ((nextLine2 = reader2.readNext()) != null) {
ArrayList<String> list2 = new ArrayList<String>();
for (int i = 0; i < 5; i++) { // 5 is the number of columns
list2.add(nextLine2[i]);
}
array2.add(list2);
}
reader2.close();
答案 0 :(得分:3)
如何声明... 功能
ArrayList<ArrayList<String>> fromFileToArray(String filename)
答案 1 :(得分:1)
List<List<String>> getList(String filePath){
CSVReader reader = new CSVReader(new FileReader(filePath));
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) { // 5 is the number of columns
list.add(nextLine2[i]);
}
array.add(list);
}
reader.close();
return array;
}
答案 2 :(得分:1)
您可以创建如下方法
ArrayList<ArrayList<String>> read (FileReader reader)
{
CSVReader reader = new CSVReader(reader);
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) { // 5 is the number of columns
list.add(nextLine[i]);
}
array.add(list);
}
reader.close();
return array;
}
然后你可以调用以下方法两次
ArrayList<ArrayList<String>> array1 = read(new FileReader(FILE_PATH));
ArrayList<ArrayList<String>> array2 = read(new FileReader(FILE_PATH2));
答案 3 :(得分:1)
public ArrayList<ArrayList<String>> getCSVContent(String filepath) throws Exception {
CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) { // 5 is the number of columns
list.add(nextLine[i]);
}
array.add(list);
}
reader.close();
return array;
}