title: Infinite loop while using Scanner to read file Java
body: <p>So I am trying to parse text files that could be in the form</p>
  
  <pre><code>words words words werdz words
  </code></pre>
  
  <p>or</p>
  
  <pre><code>words
  words
  words
  words
  words
  </code></pre>
  
  <p>Because of this, I decided to use Scanner instead of BufferedReader, and I'm not very experienced with using Scanner. I am trying to read a file and save to a Collection. Here is the main code and the supplementary methods.</p>
  
  <p>main:</p>
  
  <pre><code>public static void main(String[] args) throws IOException {
  
          LinkedList&lt;String&gt; unmodDict = readDict(new File(args[0]));
          String[] unsorted = readUnsorted(new File(args[1]));
  
          ...
  
  } 
  </code></pre>
  
  <p>readDict()</p>
  
  <pre><code>public static LinkedList&lt;String&gt; readDict(File file) throws IOException {
          //BufferedReader reader = new BufferedReader(new FileReader(file));
          Scanner s = new Scanner(new FileReader(file));
          String line = null;
          LinkedList&lt;String&gt; ll = new LinkedList&lt;&gt;();
          int count = 0;
          while(s.hasNext()) {
              ll.add(s.next());
          }
          // this loop seems to run finitely.
          s.close();
          return ll;
      }
  </code></pre>
  
  <p>readUnsorted()</p>
  
  <pre><code>public static String[] readUnsorted(File file) throws IOException {
          //BufferedReader reader = new BufferedReader(new FileReader(file));
          Scanner reader = new Scanner(new FileReader(file));
          int count = 0;
          while (reader.hasNext()) {
              count++;
          }
          reader.close();
          // The above loop is running infinitely.
  
          Scanner reader2 = new Scanner(new FileReader(file));
          String line2 = null;
          String[] unsortedWerdz = new String[count];
          int i = 0;
          while (reader2.hasNext()) {
              unsortedWerdz[i] = reader2.next();
              i++;
          }
          reader2.close();
  
          return unsortedWerdz;
      }
  </code></pre>
  
  <p>For some reason, the first while loop in the readUnsorted method is running infinitely but I can't see why since the first loop in the readDict method seems to run fine. Could someone advise me on what to do?</p>
  
  <p>Thanks</p>