/* Examples of reading and writing a single object to a text file using a class that has methods to convert to and from text */ package Files; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author achapin */ public class ReadWriteCat { // open a box to release the cat, let it grow, then put it back in the box // reads from and writes to a text file public static void main(String[] args) { Cat foreverCat = null; // attempt to read in text info about a cat from a file // representing forever cat stored in the box try { // get access to the file Scanner inFile = new Scanner( new BufferedReader( new FileReader( new File("CatBox.csv")))); // read in line from file String fileLine = inFile.nextLine(); // try to convert line to Cat foreverCat = Cat.fromCSV(fileLine); // don't forget to close the file!! inFile.close(); } catch (FileNotFoundException ex) { // things that go wrong are all part of this cat-based experiment System.out.println("Are you sure you actually put a cat in this box?") } // if there was no file or it was bad format or Schrodinger interfered, if (foreverCat == null) { System.out.println("the forever cat was lost in the abyss, but is ever reborn"); foreverCat = new Cat(); } // update info about the cat System.out.println("I give you, the forever cat: " + foreverCat); foreverCat.setAge(foreverCat.getAge() + (int)(Math.random() * 10)); foreverCat.setWeight(foreverCat.getWeight() + (Math.random() * 10)); System.out.println("Living among us, the forever cat has become: " + foreverCat); // store text information about a cat in a file // representing trying to store the cat in a box for later try { // set up to write to the file PrintWriter outFile = new PrintWriter( new BufferedWriter( new FileWriter( new File("CatBox.csv")))); // random chance of bad thing happening if (Math.random() < .9) { // turn the cat into CSV format String and write that to the file String catString = foreverCat.toCSV(); outFile.println(catString); } else { outFile.println("SCHRODINGER YOU BASTARD!!!"); } // close the file!! outFile.close(); } catch (IOException ex) { // things that go wrong are all part of this cat-based experiment System.out.println("The cat wouldn't go in the box; what can you do?") } } }