// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
// TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE
// SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
// REPAIR OR CORRECTION. IN NO EVENT WILL THE AUTHOR OR ANY OTHER PARTY WHO
// MAY HAVE DISTRIBUTED THE SOFTWARE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
// ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
// THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS
// OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
// THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER
// PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGES.

import java.io.*;
import java.util.*;

/**
 *  Sorts the lines in a file alphabetically.
 */
public class FileSorter
{
  /**
   *  Contains all lines in a file.
   */
  private List lines = new ArrayList ();

  /**
   *  Test method for this class
   */
  public static void main (String[] args)
  {
    if (args.length == 2)
    {
      FileSorter fs = new FileSorter ();
      try
      {
		long t1 = System.currentTimeMillis();
        fs.readFrom (args [0]);
        fs.sort ();
        fs.writeTo (args [1]);
		long t2 = System.currentTimeMillis();
		System.out.println("total: " + (t2 - t1) + "ms");
      }
      catch (IOException ex)
      {
        System.err.println ("Error: " + ex);
      }
    }
    else
    {
      System.err.println ("Usage: FileSorter  ");
      System.err.println (" - sorts the lines in a text file");
    }
  }

  /**
   *  Sort the {@link #lines} list.
   */
  public void sort ()
  {
     Collections.sort (lines);
  }

  /**
   *  Read all lines from a file, and store them in {@link #lines}.
   */
  public void readFrom (String filename) throws IOException
  {
    BufferedReader br = new BufferedReader (new FileReader (filename));
    String s;
    do
    {
      s = br.readLine ();
      if (s != null)
      {
        lines.add (s);
      }
    }
    while (s != null);
  }

  /**
   *  Write all elements in {@link #lines} to a file.
   */
  public void writeTo (String filename) throws IOException
  {
    FileOutputStream fos = new FileOutputStream (filename);
    for (int i = 0 ; i < lines.size() ; i++)
    {
      fos.write (((String) lines.get(i)).getBytes ());
      fos.write ((byte) '\r');
      fos.write ((byte) '\n');
    }
    fos.close ();
  }
}