2

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)

John N
  • 21
  • 2
  • Welcome to SO, John! Aside from the fact that you're only checking two of the year digits, your algorithm seems like it would succeed. Do you have a question about it? – Pops Apr 12 '10 at 18:20
  • Thank you for the welcome. I am just getting started into programming and I am trying to wrap my head around a lot of the this. – John N Apr 13 '10 at 18:25

3 Answers3

2

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.

Community
  • 1
  • 1
ring bearer
  • 20,383
  • 7
  • 59
  • 72
  • 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 Apr 13 '10 at 17:23
  • 1
    Yes, a map would not allow duplicate keys. So, you might want to change the value in map to a `List` so that the code looks like (Code given just for idea-sake; Did not compile/test) ` List records; while((line=reader.readLine())!=null){ if(map.get(getField(line) != null) { records = map.get(getField(line)); } else { records = new ArrayList(); } 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 Apr 13 '10 at 19:30
0

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
  • 66,414
  • 68
  • 253
  • 406
0

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501