// patterns/trash/ParseTrash.java // ©2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Open a file and parse its contents into // Trash objects, placing each into a List. package patterns.trash; import java.util.*; import java.util.stream.*; import java.io.*; import java.nio.file.*; import java.nio.file.Files; public class ParseTrash { public static void fillBin(String pckg, Fillable bin) { try { 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(); double weight = Double.valueOf( line.substring(line.indexOf(':') + 1) .trim()); bin.addTrash(Trash.factory( new Trash.Info(type, weight))); }); } catch(IOException | NumberFormatException | Trash.TrashClassNotFoundException | Trash.CannotCreateTrashException e) { throw new RuntimeException(e); } } // Special case to handle List: public static void fillBin(String pckg, List bin) { fillBin(pckg, new FillableList<>(bin)); } // Basic test: public static void main(String[] args) { List t = new ArrayList<>(); fillBin("trash", t); t.forEach(System.out::println); } }