OnJava8-Examples/patterns/trash/ParseTrash.java
Bruce Eckel 88dbdbbbcb update
2015-05-18 23:05:30 -07:00

41 lines
1.2 KiB
Java

//: patterns/trash/ParseTrash.java
// Open a file and parse its contents into
// Trash objects, placing each into an ArrayList.
package patterns.trash;
import java.util.*;
import java.io.*;
public class ParseTrash {
public static void
fillBin(String filename, Fillable bin) {
try {
try (BufferedReader data = new BufferedReader(
new FileReader(filename))) {
String buf;
while((buf = data.readLine())!= null) {
if(buf.trim().length() == 0)
continue; // Skip empty lines
String type = buf.substring(0,
buf.indexOf(':')).trim();
double weight = Double.valueOf(
buf.substring(buf.indexOf(':') + 1)
.trim());
bin.addTrash(Trash.factory(
new Trash.Info(type, weight)));
}
}
} catch(IOException e) {
e.printStackTrace();
} catch(NumberFormatException |
Trash.PrototypeNotFoundException |
Trash.CannotCreateTrashException e) {
e.printStackTrace();
}
}
// Special case to handle ArrayList:
public static void
fillBin(String filename, ArrayList<Trash> bin) {
fillBin(filename, new FillableList(bin));
}
} ///:~