/** * This program reads Strings from an ascii file and creates a TheDataBase object for the data. */ import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.ArrayList; public class FileIO { /** Read Strings from the file. Assumes the ascii file as the following structure: * animal name 1 (e.g. Spot) * animal type 1 (e.g. dog) * animal name 2 * * animal type 2 * etc * @param filename the name of the ascii file name * @return TheDataBase object containing all of the information in the file. */ public static TheDataBase readFile(String filename) { TheDataBase db = new TheDataBase(); try { File inputFile = new File(filename); Scanner in = new Scanner(inputFile); while(in.hasNextLine()) { String animalName = in.nextLine().trim(); // read name Animal a = new Animal(animalName); String typeName = in.nextLine().trim(); // read type Type t = new Type(typeName); a = db.addAnimal(a); // if name already in list, returns the one in list t = db.addType(t); // if type already in list, returns the one in list a.setType(t); // set the type for this animal t.addAnimal(a); // adds this animal name to the list of animals of this type } } catch (FileNotFoundException e) { System.out.println("File not found."); } return db; } }