views:

93

answers:

3

I am trying to sort the dates from the earliest to the latest. I was thinking about using the bufferedreader and do a try searching the first 2 characters of the string and then the 4th and 5th characters and finally the 7th and 8th characters, ignoring the slashes.

The following is an example of the text file I have:

04/24/2010 - 2000.0 (Deposit)

09/05/2010 - 20.0 (Fees)

02/30/2007 - 600.0 (Deposit)

06/15/2009 - 200.0 (Fees)

08/23/2010 - 300.0 (Deposit)

06/05/2006 - 500.0 (Fees)

A: 

How big is the file? I would just read in every line, create a date object for each of the lines, and then call Collections.sort(list<myobjectwithdate>)

Date provides a comparator, so you could very easily store everything in memory, sort it, and then write it back to file.

class LineAndDate implements Comparable{
  private Date date;
  private String line;

  public int compareTo( Object other )
  {
    return date.compareTo( ((LineAndDate)other).date;
  }

}

Store a List<LineAndDate> in memory, and then you should just be able to call Collections.sort(myList) and write that.

Stefan Kendall
A: 

Change your dates to the desired format using SimpleDateFormat, and sort on that.

Robert Harvey
+2  A: 

Hey take a look at this http://stackoverflow.com/questions/740936/how-do-i-sort-records-in-a-text-file-using-java

This clubbed with changing your dates to the desired format using SimpleDateFormat in getField(String line) should get you going.

ring bearer
I noticed that it did not allow for duplicate strings when I tried to run it, as per a note in that link you gave me said as well. Also, when I run the sort it puts it into a single line. As far as the SimpleDateFormat, I would use the MM/DD/YYYY I am assuming. Thanks for your help!
John N
Yes, a map would not allow duplicate keys. So, you might want to change the value in map to a `List<String>` so that the code looks like (Code given just for idea-sake; Did not compile/test)`List<String> records; while((line=reader.readLine())!=null){ if(map.get(getField(line) != null) { records = map.get(getField(line)); } else { records = new ArrayList<String>(); } records.add(line); map.put(getField(line),records);}`Similarly the loop that writes records out will deal with `List` values in the map.
ring bearer