JAVA - 将 CSV 导入到 ArrayList [英] JAVA - import CSV to ArrayList

查看:33
本文介绍了JAVA - 将 CSV 导入到 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 StringTokenizerCSV 文件导入到 Arraylist:

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 是如何工作的,因为如果我保留初始化三个变量(docNumbernoteindex) 作为 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 个逗号分隔的字段.您应该始终检查 tokenizer 是否有更多标记 (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆