2017-03-20 114 views
0

我正在嘗試從我的程序的.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 
+0

你不需要兩臺掃描儀。 [這裏是你如何做到這一點的例子。](http://stackoverflow.com/questions/14274259/java-read-csv-with-scanner) – EmptyArsenal

+0

遍歷文件,設置一個字符串等於你讀的,然後用分隔符(「,」)分割該字符串。請注意,string.split()返回一個數組,以便將結果設置爲與數組的結果相同。請享用。 – SomeStudent

+0

爲什麼你不使用poi做任何csv的東西,如果你想我可以發佈一個例子,或者你也可以谷歌它。 –

回答

0
File file = new File("C:/Users/Josh/Desktop/prog5input.csv"); 
Scanner sc = new Scanner(file); 
while(sc.hasNextLine()){ 
     String str = sc.nextLine(); 
     String[] arr = str.split(","); 
     int accountType = Integer.valueOf(((String)arr[0]).trim()); 
     ...... 
} 

你可以參考this link有關其他方法來讀取文件。

+0

這可能已經足夠用於許多用途。但是,如果某些字段可能包含逗號(在這種情況下該字段將用引號括起來),它會中斷。對於一般用途,最好查看一個CSV庫。 – ajb

+0

是的,很好的評論。 –

0

你可以通過溢出的方法將它設置爲實際的字符串,然後到一個ArrayList的:

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