10 Replies Latest reply: Mar 27, 2007 1:58 AM by EJP RSS

    Smething wrong when closing/deleting a BufferedWriter stream. Locked file?

    807606
      Hi there,

      I tried to write an app which writes into a file while reading from another. I used:

      BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, false));

      and the same with the BufferedReader.

      The strange thing is that I close the file with bw.close(); and when I try to delete it using the file.close(), where file is an instance of the File class, sometimes it allows me and some other times don't.

      I did some loops and the behaviour was just always the same but impredictable. With a loop of 7 it could delete it 3 times while the other 4 it couldn't (close() method returned false). With a loop of 3 it could delete just the first one while getting false again with the last 2 tries.

      I don't know if I am expressing myself right. First I thought that it was a synchronized thing so I put some blocks or declared the methods as synchronized but it didn't work.

      So how can I solve it? It happens the same if I don't use a Buffer and use FileInputStream & FileOutputStream directly.

      Here's a little pseudocode of what the code was:

      for (int i = 0; i < vector.size(); i++)
      {

      // open file and read line by line with BufferedReader
      // write each line with a BufferdWriter to a temp file
      // copy the temp file to another one
      // delete the temp file ---> HERE IT GOES WRONG!!

      if (!file.delete())
      {
      System.out.println("ERROR: deleting the file: " + fileName);
      }

      }


      Reading from:

      http://forum.java.sun.com/thread.jspa?forumID=17&threadID=538035

      It seems to be explained now but... then it's some kind of BUG?!!!

      What I did was:


      public class A {
      public static void main(String[] args) throws FileNotFoundException, IOException {
      File f = new File("deletem");
      FileOutputStream fos = new FileOutputStream(f);
      fos.write(1);
      fos.close();
           fos=null; //make sure it can be deleted by //GarbageCollector
      System.gc() // run the Garbage Collector
      System.out.println("exists="+f.exists());
      System.out.println("delete="+f.delete());
      System.out.println("exists="+f.exists());
      }
      }




      Cheers and thanks!

      Richis

      Edited by Richis
        • 1. Re: Something wrong when closing a BufferedWriter stream. Locked file?
          807606
          How do you actually copy the temp file to another one ?
          (And why don't you write to that another one directly instead of writing to a temp file and copying it afterward ?)
          • 2. Re: Something wrong when closing a BufferedWriter stream. Locked file?
            807606
            Hi thanks in advance for answering so soon! Here's what I do:
            for (int i = 0; i < fileList.size(); i++)
                      {
                           
                           System.out.println("I start the " + fileList.elementAt(i).getHostName() + " hostname file");
            
                           RenameRules renameRules = new RenameRules();
                           renameRules.setHostName(fileList.elementAt(i).getHostName());
                           
                           System.out.println("I execute the rename rule...");
                           rc = new RuleContext(renameRules, fileList.elementAt(i).getInputFile(), "C:\\temp\\temp.log");
                           rc.runRule();
                           
                           RemoveRules removeRules = new RemoveRules();
                           
                           rc = new RuleContext(removeRules, "C:\\temp\\temp.log", "C:\\temp\\temp2.log");
                           rc.runRule();
                           
                           rc = new RuleContext(new CopyFileRule(), "C:\\temp\\temp2.log", fileList.elementAt(i).getFinalFile());
                           rc.runRule();
                           
                           
                           FileOperator.removeTempFile("C:\\temp\\temp2.log");
                           FileOperator.removeTempFile("C:\\temp\\temp.log");
            
                      }
            What it does is applying some rules to several apache log files. That's why there is a for statement. It should process every file.

            And with every file it should process every Rule (rename, remove, etc.).

            The thing is that every rule reads from one input and writes to an output. And I need a pipe there so that rule1 outputs to rule2 and rule2 to rule3. And then finally I have one input file and few output files where I am only interested in the first and last ones. The middle ones should be temp files and that's why I need to delete them.

            I copy them using another custom Rule CopyFileRule. It reads from one input and writes to an output.

            I hope this can be understood. If not please let me know.

            All suggestions are welcome. Of any kind :) If you have another idea on how this problem can be solved, another pattern, please let me know. I am always glad to learn.

            Thanks again for your fast answer!

            Richis
            • 3. Re: Something wrong when closing a BufferedWriter stream. Locked file?
              abillconsl
              Take this simple example:
              import java.io.*;
              
              public class TestIfClosed {
                public static void main(String[] argv)  throws Exception {
                  File AB = new File("ab.txt");
                  BufferedWriter bw = new BufferedWriter(new FileWriter(AB,false));
                  for (int i = 1; i < 100; i++) {
                    bw.write("  "+i);
                    bw.newLine();
                  }
              /*    if (bw != null ) {
                    bw.close();
                    bw = null;
                  }
              */    if ( !AB.delete() )
                    System.out.println("N/G");
                  else
                    System.out.println("Good close");
                }
              }
              If you run it like it is it will always print N/G. If you uncomment those lines, it will always - for me at least - print 'Good close'. So something is not being released somewhere. You need to find out where ... you can do it! - we can help.

              ~Bill
              • 4. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                807606
                wild and crazy idea, but try flushing before you close.
                • 5. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                  796447
                  wild and crazy idea, but try flushing before you
                  close.
                  That would be superfluous, as close() (on buffered types of streams anyway) ends up invoking flush as part of its operation.
                  • 6. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                    807606
                    RIght, but one of the examples was a FileOutputStream, not sure how that played into the mix.
                    • 7. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                      796447
                      RIght, but one of the examples was a
                      FileOutputStream, not sure how that played into the
                      mix.
                      FileOutputStream's flush() method is inherited directly from OutputStream, which does nothing.

                      What I'm saying is, it's never necessary to invoke flush() before invoking close().
                      • 8. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                        807606
                        Well, thanks everybody for helping me. It's great to communicate like this... helping each other out. I just could make it work running System.gc() and creating a delay. It's crazy but that works...

                        Thanks a lot again,


                        Richis
                        • 9. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                          807606
                          Try reading this link:

                          http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6266377
                          • 10. Re: Something wrong when closing a BufferedWriter stream. Locked file?
                            EJP
                            In other words make sure you aren't swallowing an exception on writing or closing and still trying to do the rename and delete. That would be incorrect anyway as the output would be incomplete.