前言:这是我的一门课的作业。
我需要解析 CSV 文件并将每个字符串添加到 ArrayList,以便我可以使用预编码函数单独与每个字符串进行交互。
我的问题是,每行中的最后一个字符串(不以逗号结尾)与下一行中的第一个字符串组合在一起,并被识别为位于 ArrayList 中的相同索引处。我需要学习如何添加换行符或执行其他操作以在每行末尾停止循环并单独读取下一行。也许扫描仪类中有一个我不知道的内置方法可以为我做到这一点?感谢帮助!
以下是 CSV 文件中的信息:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
这是我到目前为止的代码
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
这是输出
7/16/2002
Michael
最佳答案
看来你只需要做...
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);
关于Java - 将CSV解析为ArrayList(需要识别换行符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26519816/