title: Fastest way of reading a CSV file in Java
body: <p>I have noticed that using <code>java.util.Scanner</code> is very slow when reading large files (in my case, CSV files).</p>
  
  <p>I want to change the way I am currently reading files, to improve performance. Below is what I have at the moment. Note that I am developing for Android:</p>
  
  <pre><code>InputStreamReader inputStreamReader;
      try {
          inputStreamReader = new InputStreamReader(context.getAssets().open("MyFile.csv"));
          Scanner inputStream = new Scanner(inputStreamReader);
          inputStream.nextLine(); // Ignores the first line
          while (inputStream.hasNext()) {
              String data = inputStream.nextLine(); // Gets a whole line
              String[] line = data.split(","); // Splits the line up into a string array
  
              if (line.length &gt; 1) {
                  // Do stuff, e.g:
                  String value = line[1];
              }
          }
          inputStream.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  </code></pre>
  
  <p>Using <a href="http://developer.android.com/tools/debugging/debugging-tracing.html" rel="nofollow noreferrer">Traceview</a>, I managed to find that the main performance issues, specifically are: <code>java.util.Scanner.nextLine()</code> and <code>java.util.Scanner.hasNext()</code>.</p>
  
  <p>I've looked at other questions (such as <a href="https://stackoverflow.com/questions/6857248/fast-csv-parsing">this one</a>), and I've come across some CSV readers, like the <a href="http://commons.apache.org/proper/commons-csv/index.html" rel="nofollow noreferrer">Apache Commons CSV</a>, but they don't seem to have much information on how to use them, and I'm not sure how much faster they would be.</p>
  
  <p>I have also heard about using <code>FileReader</code> and <code>BufferedReader</code> in answers like <a href="https://stackoverflow.com/a/4716521/4230345">this one</a>, but again, I do not know whether the improvements will be significant.</p>
  
  <p>My file is about 30,000 lines in length, and using the code I have at the moment (above), it takes at least 1 minute to read values from about 600 lines down, so I have not timed how long it would take to read values from over 2,000 lines down, but sometimes, when reading information, the Android app becomes unresponsive and crashes.</p>
  
  <p>Although I could simply change parts of my code and see for myself, I would like to know if there are any <strong>faster alternatives</strong> I have not mentioned, or if I should just use <code>FileReader</code> and <code>BufferedReader</code>. Would it be faster to split the huge file into smaller files, and choose which one to read depending on what information I want to retrieve? Preferably, I would also like to know <strong>why the fastest method is the fastest</strong> (i.e. what makes it fast).</p>