import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.util.ArrayList; import java.util.List; /******************************************************************************* * Třída CarIO pro čtení a záznam seznamu aut do text. souboru. * * @author Tomáš Pitner * @version 1.00, 10.8.2005 */ public class CarIO { private File carFile; /*************************************************************************** * */ public CarIO(File cf) { carFile = cf; } public List readCars() throws IOException { List lc = new ArrayList(); Car c = null; FileReader fr = new FileReader(carFile); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while (line != null) { if(line.startsWith("Truck")) { // read/create a Truck String label = line.substring("Truck ".length(), "Truck ".length() + 7); double maxLoad = readDouble(line.substring("Truck ".length() + 8)); c = new Truck(label, maxLoad); } else if(line.startsWith("Private car")) { // read/create a Private car String label = line.substring("Private car ".length(), "Private car ".length() + 7); int seats = readInt(line.substring("Private car ".length() + 8)); c = new PrivateCar(label, seats); } else { throw new IOException("Cannot read a Car of an unknown type."); } lc.add(c); line = br.readLine(); } br.close(); return lc; } public void writeCars(List lc) throws IOException { FileWriter fw = new FileWriter(carFile); PrintWriter pw = new PrintWriter(fw); for(Car c: lc) { pw.println(c.asRecord()); pw.flush(); } pw.close(); } protected static int readInt(String s) { return Integer.parseInt(s); } protected static double readDouble(String s) { return Double.parseDouble(s); } }