提问人:chriscondreay 提问时间:3/24/2023 更新时间:3/24/2023 访问量:48
使用 database 和 fieldFilter 参数解析 CSV
Parse CSV using database and fieldFilter parameters
问:
我使用ArrayList创建了一个方法,该方法从CSV文件构建列表。我无法将字段的 String 值添加到列表中。当我尝试使用 field.add() 时,它给了我一个错误“对于 String 类型,add(String) 方法未定义”。如何解决此问题并使其可以将 String 值添加到列表中并返回 ArrayList?
/**
* This method begins by creating a new ArrayList of Strings. It then
* attaches a Scanner to the provided File object and uses a while
* loop to process the file line-by-line. For each line, this method creates
* a new Scanner object with a comma "," delimiter to to enable access the
* individual fields within the line using a second, inner while loop. As each
* field is processed it is tracked using a counter variable starting with
* field 1. If the current field is equal to the specified fieldFilter, the
* String value of the field is added to the list. Once all the lines in the
* file have been processed, the ArrayList is returned to the caller.
*
* If Scanner throws a FileNotFoundException when instantiating the new file
* Scanner object, catch the expection, display an error message, and exit
* the program immediately with an exit status of 1.
*
* @param csvFile File object that contains the CSV database to process
* @param fieldFilter Field number to use for building the list
* @return ArrayList of strings that represents the desired column of data from the database.
*/
public static ArrayList<String> buildListFromCSV(File database, int fieldFilter) {
final int ERROR_CODE = 1;
try {
Scanner fileScanner = new Scanner(database);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
int fieldCounter = 1;
while (lineScanner.hasNext()) {
String field = lineScanner.next();
if (fieldCounter == fieldFilter) {
field.add();
}
fieldCounter++;
}
lineScanner.close();
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("Unable to open file: " + database);
System.exit(ERROR_CODE);
}
return field;
}
答: 暂无答案
评论
field.add
List