从逗号分隔值文件中读取

时间:2017-03-20 02:25:41

标签: java csv

我正在尝试从.csv文件中读取我的程序,但我们之前从未读过.csv文件。我不太清楚如何去做,但这是我到目前为止的尝试。我想我错过了某种循环,它循环遍历文件的每一行但我不知道如何去做。

Bank bank = new Bank();
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
Scanner s2 = new Scanner(infile.nextLine());
int accountType = 0;
String accountHolder = "";
double accountInitial = 0.0;
double accountRate = 0.0;
System.out.println("Program 5, Josh Correia, cssc0491");

System.out.println("Creating accounts...");
s2.useDelimiter(",");
if (s2.hasNextInt()) accountType = s2.nextInt();
if (s2.hasNext()) accountHolder = s2.next();
if (s2.hasNextDouble()) accountInitial = s2.nextDouble();
if (s2.hasNextDouble()) accountRate = s2.nextDouble();

bank.addNewAccount(new SavingsAccount(accountHolder, accountInitial, accountRate));

感谢任何帮助,谢谢:)

这是我正在阅读的文件:

1,Waterford Ellingsworth, 4350.0, 0.002
2,Bethanie Treadwell, 500.0, 0.35
3,Ira Standish, 50000, 0.1, 59, 0.1
4,Debi Cardashian, 5100, 0.0

2 个答案:

答案 0 :(得分:0)

  alfa   beta   ceta
1  a,b  d,e,f  g,h,k
2  j,k  c,k,l  f,k,n

您可以参考this link了解其他阅读文件的方法。

答案 1 :(得分:0)

您可以将其设置为实际的String,然后通过溢出方法将其设置为ArrayList:

String str = " ";
ArrayList<String> elephantList = Arrays.asList(str.split(","));