OnJava8-Examples/patterns/trash/ParseTrash.java

48 lines
1.4 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/trash/ParseTrash.java
2015-06-15 17:47:35 -07:00
// Open a file and parse its contents into
2015-11-03 12:00:44 -08:00
// Trash objects, placing each into a List.
2015-06-15 17:47:35 -07:00
package patterns.trash;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
import java.io.*;
2015-09-07 16:34:48 -06:00
import java.nio.file.*;
2015-11-03 12:00:44 -08:00
import java.nio.file.Files;
2015-06-15 17:47:35 -07:00
public class ParseTrash {
public static <T extends Trash> void
2015-11-03 12:00:44 -08:00
fillBin(String pckg, Fillable<T> bin) {
2015-06-15 17:47:35 -07:00
try {
2015-11-03 12:00:44 -08:00
Files.lines(Paths.get("..", "trash", "Trash.dat"))
// Remove empty lines and comment lines:
.filter(line -> line.trim().length() != 0)
.filter(line -> !line.startsWith("//"))
.forEach( line -> {
String type = "patterns." + pckg + "." +
line.substring(
0, line.indexOf(':')).trim();
2015-06-15 17:47:35 -07:00
double weight = Double.valueOf(
2015-11-03 12:00:44 -08:00
line.substring(line.indexOf(':') + 1)
.trim());
2015-06-15 17:47:35 -07:00
bin.addTrash(Trash.factory(
new Trash.Info(type, weight)));
2015-11-03 12:00:44 -08:00
});
2015-06-15 17:47:35 -07:00
} catch(IOException |
NumberFormatException |
2015-11-03 12:00:44 -08:00
Trash.TrashClassNotFoundException |
2015-06-15 17:47:35 -07:00
Trash.CannotCreateTrashException e) {
throw new RuntimeException(e);
}
}
2015-11-03 12:00:44 -08:00
// Special case to handle List:
2015-06-15 17:47:35 -07:00
public static <T extends Trash> void
2015-11-03 12:00:44 -08:00
fillBin(String pckg, List<T> bin) {
fillBin(pckg, new FillableList<>(bin));
}
// Basic test:
public static void main(String[] args) {
List<Trash> t = new ArrayList<>();
fillBin("trash", t);
t.forEach(System.out::println);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}