【问题标题】:Transform a CSV file into a list<list<String>> [duplicate]将 CSV 文件转换为列表<list<String>> [重复]
【发布时间】:2015-07-29 20:15:56
【问题描述】:

我的本​​地服务器中有一个 CSV 文件,我想读取该文件并将其转换为 list&lt;list&lt;String&gt;&gt;。我已经完成了与服务器的连接部分,现在我想读取这个 csv 文件并对其进行转换。

谁能给我看一个这种转换的例子,因为大多数例子都展示了如何将它转换成多维数组?

【问题讨论】:

  • 对于每个 raw 获取逗号分隔的字符串作为一个列表,然后将所有 raw 作为一个列表。
  • 你可以使用Jackson来处理CSV文件cowtowncoder.com/blog/archives/2012/03/entry_468.html
  • 链接的答案是关于逗号分隔的字符串,而这个问题是关于不同的 CSV 文件(CSV 文件具有在值中包含逗号的机制)。这个答案出现在谷歌,所以尽管这个答案被关闭,我还是在这里发布警告

标签: java list csv


【解决方案1】:

这是您正在寻找的一个非常简单的示例,ArrayList&lt;List&lt;String&gt;&gt; linesArrays 是每一行的项目列表。

public class FileReader
{
  public static void main(String args[])
  {
    ArrayList<List<String>> linesArrays = new ArrayList<List<String>>();

    FileInputStream fileInputStream = null;
    BufferedReader bufferedReader = null;
    try
    {
      fileInputStream = new FileInputStream("d:\\test.csv");
      bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

      String line = bufferedReader.readLine();
      while (line != null)
      {
        line = bufferedReader.readLine();
        if (line != null)
        {
          List<String> items = Arrays.asList(line.split(","));
          linesArrays.add(items);
        }
      }
      for (List<String> stringList : linesArrays)
      {
        System.out.println("items :" + stringList.size());
      }
    }
    catch (FileNotFoundException fileNotFoundException)
    {
      //todo Deal with exception
      fileNotFoundException.printStackTrace();
    }
    catch (IOException iOException)
    {
      //todo Deal with exception
      iOException.printStackTrace();

    }
    finally
    {
      try
      {
        if (bufferedReader != null)
        {
          bufferedReader.close();
        }
        if (fileInputStream != null)
        {
          fileInputStream.close();
        }
      }
      catch (IOException ex)
      {
        // not much you can do about this one
      }
    }
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2018-08-27
    • 2012-11-05
    • 2020-04-29
    • 1970-01-01
    • 2019-07-28
    • 2020-03-17
    相关资源
    最近更新 更多