0

I have created a temp file, written to it and I want to overwrite the existing file

  1. Create temp file
  2. Fill it up
  3. Open old file
  4. Set old file to equal new one

Here is my code, but it is not working

Please let me know if you can find the issue. Thank you!

try{
            //create a temporary file
            File temporary=File.createTempFile("tmp", "");
            BufferedWriter writer = new BufferedWriter(new FileWriter(temporary));
            //Write each line to file (temporary)
            for (String string : parsedArticlesToSave) {
                writer.write (String.format("%s\n", string));
            }
            //load old file
            File oldFile = new File("StringFile/ArticlesDB.txt");
            //replace old file with new file
            oldFile=temporary;
            //release resources
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
William Falcon
  • 9,813
  • 14
  • 67
  • 110

1 Answers1

1

I think you misunderstand the whole concept of class java.io.File

and don't understand the concept of variable assignment in Java.

Making the object of this class java.io.File creates a kind of pointer on the file, so that you can operation with it "at the whole"

So what you did by 'oldFile = temporary' is just made your pointer to oldFile to point on temporary one. But this is only done in the context of variable assignment in Java, it doesn't have any impact on the actual filesystem.

Now regarding the variable assignment.

Take it with objects: Lets say you have two integers:

Integer a = 5;
Integer b = 10;

By doing 'b = a' you don't actually change the object b itself, but instead your reference to object b becomes a reference to object a. The old value of the object b is still stored in memory, but since after the assignment no one points (refers) to it, it becomes inaccessible and will be garbage collected eventually.

Now regarding the solution itself: You should really copy the content of the file temp to the old one line by line byte by byte) or if you just want to make the old file to have the same content and you don't really need a temporary file just to delete the file and then rename the temporary file to be 'oldFile'.

Here is a link of how to use rename in java: Renaming in Java

Hope this helps

Community
  • 1
  • 1
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97