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

By : Kat
Source: Stackoverflow.com

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";

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.");

And where it is called in my runMenu Method:

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


When you open the file by passing a File object into the Print Writer you're essentially letting the PrintWriter govern how the file is opened (most likely Create) which deletes the existing file and readies a new one for a write.

Because you never save (close the stream), any data buffered in the PrintWriter isn't outputted to the file.

You need to refactor your file approach, if you use the File.Open(...) function you can specify an append session.

FileStream outStream = File.Open(myFileName, FileMode.Append);
PrintWriter pw = new PrintWriter(outStream);

This way your file wont be cleared just by opening to it, and you may append to the end.

Alternatively you can force the file to be cleared when you want it to be by opening it with FileMode.Create

P.S. you should learn about the using block, it's very usefull.

By : Aren

Make sure that you are closing your streams. Also check that you are not overwriting the original file. Aren B gave some C# code, but the Java equivalent would be:

PrintWriter printWriter = new PrintWriter( new FileWriter("path/to/album.dat", true));
By : YGL

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..

By : Jack

This video can help you solving your question :)
By: admin