Person.java

 1: // This is simplified code (an outline really) to read a file
 2: // and build a List of "Person"s.  The file format for this is
 3: // also simple:  one person record per line, each record has
 4: // two fields separated with a space: an int ("ID number") and
 5: // a String (a single word "name").
 6: //
 7: // Written 4/2009 by Wayne Pollock, Tampa Florida USA
 8: 
 9: import java.io.*;
10: import java.util.*;
11: 
12: public class Person {
13:    private final static String FILE = "People.txt";
14: 
15:    private static List<Person> people = new ArrayList<Person>();
16: 
17:    private int IDnum;
18:    private String name;
19: 
20:    public Person ( int id, String name ) {
21:       IDnum = id;
22:       this.name = name;
23:    }
24: 
25:    public String toString () {
26:       return "ID " + IDnum + ": " + name;
27:    }
28: 
29:    public static void main ( String [] args ) {
30:       Scanner data = null;
31:       try { data = new Scanner( new File (FILE) ); }
32:       catch ( FileNotFoundException e ) {
33:          System.err.println( "File \"" + FILE + "\" Not Found!");
34:          System.exit(1);
35:       }
36: 
37:       int IDnum;
38:       String name;
39: 
40:       while ( data.hasNextInt() ) {
41:          IDnum = data.nextInt();
42:          name = data.next();
43:          people.add( new Person(IDnum, name) );
44:       }
45:       data.close();
46: 
47:       // Now let's prove we read in the data correctly:
48:       System.out.println( people.size() + " records read:\n" );
49:       System.out.println ( people );
50:    }
51: }