OO Programming with Java


Buffers & Writers (Readers)

As an application, the bookstore example can now be extended with save/load capabilities:

public void save(String filename) throws IOException {
  try (FileWriter file = new FileWriter(filename)) {
    for(Product book : this)
      file.write(book.getName()+","+book.getPrice()+","+book.getQuantity()+"\n");
  }
}

public void load(String filename) throws IOException {
  try (BufferedReader file = new BufferedReader(new FileReader(filename))) {
    while (file.ready()) {
      String[] data = file.readLine().split(",");
      this.add(new Product(data[0],Double.parseDouble(data[1]),Integer.parseInt(data[2])));
    }
  }
} 

9 - 12