Search code examples
javafilewriter

Why is my file being cleared if I don't save it?


My program is suppose to maintain a collection of Photos in a PhotoAlbum. It begins by reading a folder of photos and adds them to my PhotoAlbum. It then prints a menu that allows the user to list all the photos, add a photo, find a photo, save, and quit the program. Right now if I run my program it will add the 100 photos to the PhotoAlbum, but if I quit the program without saving, it clears the file I am reading from even if I haven't added a photo or done anything to the PhotoAlbum and I'm not sure why.

Here is my method for printing to a file:

private static void saveFile(PrintWriter writer) {
 String result;
  ArrayList<Photo> temp = album.getPhotoAlbum();
  for (int i = 0; i < temp.size(); i++){
   result = temp.get(i).toString() + "\n";
   writer.println(result);
  }
  writer.close();
 }

And where the PrintWriter is instantiated:

File file = new File(args[0] + File.separator + "album.dat");

try {
   PrintWriter fout =  
new PrintWriter(new FileWriter(file));
   fileWriter = fout;
  } catch (IOException e){
   System.out.println("ReadFromFile: Folder " + args[0]
                          + " is not found.");
   System.exit(0);
  }

And where it is called in my runMenu Method:

private static void runMainMenu(Scanner scan) {
  String input;
  do {
   showMainMenu();
  input = scan.nextLine().toLowerCase();
  switch (input.charAt(0)) {
  case 'p':
   System.out.println(album.toString());
   break;
  case 'a': 
  album.addPhoto(readPhoto(scan, t));
   break;
  case 'f':
  findMenu(scan);
   break;
  case 's':
   saveFile(fileWriter);
   System.exit(0);
   break;
  case 'q':
   break;
  default:
   System.out.println("Invalid entry: " + 
     input.charAt(0));
   break;
  }
  } while (!input.equalsIgnoreCase("q"));
 }

Solution

  • Probably you are not closing the stream after having opened it. You should do it in any case (not just when you actually modify it) if it has been opened..

    That's why finally blocks are useful in java, take a look here for good practices about using java streams..