0

I have a CSV file in my local server and I want to read this file and transform it into a list<list<String>>. I have done the connection part with the server now I want to read this csv file and transform it.

Can anybody show me an example of this transformation because most of the examples show how to transform it into multi-dimensional arrays?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • For each raw get the comma separated Strings as a List then make all raws as a list. – Estimate May 18 '15 at 11:02
  • You can use Jackson to hande CSV files http://www.cowtowncoder.com/blog/archives/2012/03/entry_468.html – Simon May 18 '15 at 11:45
  • The linked answer is about comma separated strings whereas this question is about CSV files which are different (CSV files have mechanisms for having a comma in a value). This answer came up in google so I'm posting a warning here despite this answer being closed – BoredAndroidDeveloper Nov 06 '19 at 15:09

1 Answers1

-1

Here is a very simple example of what you are looking for , the ArrayList<List<String>> linesArrays is the list of items for every line.

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
      }
    }
  }

}
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26