title: How do I merge individual files into a single sorted file?
body: <p>I've a bunch of id's in 4 files a,b,c,d saved in my workspace. I want to merge all these id's in a sorted order in a single file merged.txt .. They will be saved one per line as a string. I could individually sort files by bringing them into memory. But how do I merge them, there can be duplicate entries. I can't think of how to compare each entry in the four files (they can grow to 8 so can't hardcode this). Particularly how do I compare the entries and how do I advance only those file pointers that are the smallest of the entries ? </p>
  
  <pre><code>public void sortFile() throws IOException
  {
      File a = new File("/Users/phoenix/workspace/data/a.txt");
      File b = new File("/Users/phoenix/workspace/data/b.txt");
      File c = new File("/Users/phoenix/workspace/data/c.txt");
      File d = new File("/Users/phoenix/workspace/data/d.txt");
  
      doSort(a);
      doSort(b);
      doSort(c);
      doSort(d);
  
      merge();
  }
  </code></pre>
  
  <p><strong>How do I modify the merge method according to pseudocode below ?</strong> </p>
  
  <pre><code>public void merge()
  {
      File dir = new File("/Users/phoenix/workspace/data");
  
      for(File f: dir.listFiles())
      {
          // toDo: merge into a single file merged.txt
      }
  }
  
  public void doSort(File f) throws IOException
  {
      BufferedReader reader = new BufferedReader(new FileReader(f));
      String line;
      ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
      while((line = reader.readLine())!=null)
      {
          list.add(line);
      }
  
      Collections.sort(list);
  
      PrintWriter out = new PrintWriter(f);
  
      for(String s:list)
      out.println(s);
  
      reader.close();
      out.close();
  }
  
  
      public void merge() throws IOException
      {
          File dir = new File("/Users/phoenix/workspace/data");
          File merged = new File("/Users/phoenix/workspace/data/merged.txt");
  
          ArrayList&lt;BufferedReader&gt; readers = new ArrayList&lt;BufferedReader&gt;(dir.listFiles().length);
          ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
          PrintWriter out = new PrintWriter(merged);
  
          for(File f: dir.listFiles())
          {
              readers.add(new BufferedReader(new FileReader(f)));
          }
  
          while(true)
          {
          for (BufferedReader reader: readers)
          {
              if(reader.readLine()!=null)
                  list.add(reader.readLine());
  
              else
              {
                  reader.close();
              }
  
          }
  
          String min = Collections.min(list);
          int index = list.indexOf(min);
          out.write(min);
      }
  
  
  
   }
  </code></pre>