tempfile gives wrong absolutepath after renameto

I'm changing contents of a file, therefore I read a file line by line, replace what I want and write line by line to a tempfiles. When the whole file is processed, I delete the original file, and rename the tempfile to the original filename. like this

File orginialFile = new File("C:\\java\\workspace\\original.xml");
File tempFile = File.createTempFile("tempfile", ".tmp", new File(C:\\java\\workspace\\"));
while ((str_String = reader.readLine()) != null) {
//read lines and replace and write lines
orginialFile .delete();     
tempFile.renameTo(new File("C:\\java\\workspace\\original.xml"));

After this is done, I request the absolutepath (tempFile.getAbsolutePath();) of the temp file. But this gives me c:\java\workspace\tempfile3729727953777802965.tmp (the number changes every run of the program) in stead of c:\java\workspace\original.xml

How come?

I debugged it and just before the moment that I request the absolutepath, I checked in c:\java\workspace (windows explorer) and there is no tempfile. Only original file.

So the process runs correctly, I just wanted to know why it is not showing the renamed absolutepath. (I would use it for logging)



In the documentation of java.io.File, before the Interoperability with java.nio.file package:

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

So it won't show the renamed absolutepath.

There is a missing reader.close() before the delete. Likely edited out for us. Also you can do:


Have you checked the return value from renameTo()? I suspect it to be false.

Also pay attention to the api documentation. It states that a lot of things can go wrong - e.g. moving between file systems.

You might be better off with Files.move

Need Your Help

BDD Automation with Cross Browser Testing?

java selenium-webdriver cucumber-jvm

How do I achieve Cross browser testing using Selenium with any BDD tool which can coded in Java.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.