将CSV文件转换为列表<list <string>&gt;

时间:2015-05-18 10:52:31

标签: java list csv

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

有人能告诉我这个转换的例子,因为大多数例子都展示了如何将它转换成多维数组吗?

1 个答案:

答案 0 :(得分:0)

以下是您要查找的内容的一个非常简单的示例,ArrayList<List<String>> 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
      }
    }
  }

}