Import/Sort Text File With Java

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

  1. macrumors member

    MacMuttonchops

    Joined:
    Jun 5, 2008
    Messages:
    73
    Location:
    New York, NY
    #1
    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!

    Thanks,
    Matt
     
  2. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Messages:
    1,448
    Location:
    Sydney
    #2
    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):
    Code:
    001\tJohn\t23
    002\tMary\t47
    
    A more complex, but more flexible format, would be something like this:
    Code:
    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.
    Code:
    <?xml version='1.0' encoding='utf-8'?>
    <people>
     <person id='001'>
      <name>John</name>
      <age>23</age>
     </person>
     <person id='002'>
      <name>Mary</name>
      <age>47</age>
     </person>
    </people>
    

    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