Import/Sort Text File With Java

Discussion in 'Mac Programming' started by MacMuttonchops, Dec 5, 2011.

  1. MacMuttonchops macrumors member


    Jun 5, 2008
    New York, NY
    Hey guys and gals,

    Having an issue here that I thought would be simple enough, but it turns out I'm rustier than I thought. I need to import a a text file into a Java program with multiple records (e.g. name, ID, age) and I want to sort those records in ascending order by ID number. So I'd somehow have to set a "key" stating to sort by that, but keep all the other information associated with that ID number when it's sorted. Any ideas on how to format the text file (001, John, 23; 002, Mary, 47... or however, that was just a guess) and let the Java program know that the ID number is the one to sort by? Drawing a blank here!

  2. jiminaus macrumors 65816


    Dec 16, 2010
    A delimited, fixed format file should be easy to produce. These are really easy to read/write. The most common delimited, fixed formats are comma or tab delimited files. For example, (where \t represents tab characters):
    A more complex, but more flexible format, would be something like this:
    ID: 001
    Name: John
    Age: 23
    ID: 002
    Name: Mary
    Age: 47
    And of course you could always use XML. You can use the XML API that are standard parts of Java to read/write XML files.
    <?xml version='1.0' encoding='utf-8'?>
     <person id='001'>
     <person id='002'>

    In any case, you'd want to code a Person class that has id, name, age, etc. properties. Have the Person class implement the java.util.Comparable<Person> interface and implement compareTo(Person) to compare based on id.

    Then you could load the file into a collection, sort the collection, and then write the collection out again.

Share This Page