Sorting text file by date - Date looks like DD / MM / YYYY

I am trying to sort dates from earliest to latest. I was thinking about using a buffered reader and tried to search for the first two characters of the string, then the 4th and 5th characters, and finally the 7th and 8th characters, ignoring the forward slashes.

Below is an example of a 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)

+2


source to share


3 answers


How to sort records in a text file using Java?



This club with date changes to the right format with help SimpleDateFormat

in getField(String line)

should catch you.

+2


source


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

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



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

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

}

      

Store List<LineAndDate>

in memory and then you should just call Collections.sort(myList)

and write this.

0


source


Change the dates to your preferred format using SimpleDateFormat and sort.

0


source







All Articles