JAVA - CSV导入到ArrayList的 [英] JAVA - import CSV to ArrayList
问题描述
我想进口 CSV
文件复制到的ArrayList
使用的StringTokenizer
:
I'm trying import CSV
file to Arraylist
using StringTokenizer
:
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
, 注意
和首页
)为的nextToken()
,它失败于:
I don't understand how the nextToken
works, because if I keep the initialize three variables (docNumber
, note
and index
) as nextToken()
, it fails on:
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at _test.Test.main(Test.java:32)
如果我只保留docNumber,它的工作原理。你能帮助我吗?
If I keep docNumber only, it works. Could you help me?
推荐答案
看来,一些输入文件的行具有小于3逗号分隔fields.You应经常检查,如果标记生成器有更多的令牌(StringTokenizer.hasMoreTokens) ,除非你是100%肯定您的输入是正确的。
It seems that some of the rows of your input file have less then 3 comma separated fields.You should always check if tokenizer has more tokens (StringTokenizer.hasMoreTokens), unless you are are 100% sure your input is correct.
CSV文件正确解析也不是那么简单的任务。为什么不使用库,可以做的非常好 - http://opencsv.sourceforge.net/
CORRECT parsing of CSV files is not so trivial task. Why not to use a library that can do it very well - http://opencsv.sourceforge.net/ ?
这篇关于JAVA - CSV导入到ArrayList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!