我使用StringTokenizer
嘗試導入CSV
文件Arraylist
:JAVA - 導入CSV到ArrayList的
public class Test
{
public static void main(String [] args)
{
List<ImportedXls> datalist = new ArrayList<ImportedXls>();
try
{
FileReader fr = new FileReader("c:\\temp.csv");
BufferedReader br = new BufferedReader(fr);
String stringRead = br.readLine();
while(stringRead != null)
{
StringTokenizer st = new StringTokenizer(stringRead, ",");
String docNumber = st.nextToken();
String note = st.nextToken(); /** PROBLEM */
String index = st.nextToken(); /** PROBLEM */
ImportedXls temp = new ImportedXls(docNumber, note, index);
datalist.add(temp);
// read the next line
stringRead = br.readLine();
}
br.close();
}
catch(IOException ioe){...}
for (ImportedXls item : datalist) {
System.out.println(item.getDocNumber());
}
}
}
我不明白是怎麼nextToken
的作品,因爲如果我把初始化三個變量(docNumber
,note
和index
)作爲nextToken()
,它失敗的:
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at _test.Test.main(Test.java:32)
如果我繼續docNumber只是,它的工作原理。你可以幫幫我嗎?
爲什麼你不使用'stringRead.split(「,」)'? – Thomas
顯示典型的行 – duffymo
opencsv庫使讀取csv文件變得非常簡單,無需編寫自己的代碼。 – Pete855217