【发布时间】:2014-12-18 15:11:09
【问题描述】:
前言:这是我的一门课的作业。
我需要解析一个 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
【问题讨论】:
-
如果可以的话,以OpenCSV 之类的专用库为例...
-
在分隔符列表中使用
\n或\r或两者的组合。 -
我会使用Apache Commons CSV解析器项目。
-
我尝试添加换行符和回车转义序列,它成功了!谢谢你,@Mohammad