• Post Reply Bookmark Topic Watch Topic
  • New Topic

Issue reading a file after renaming it.  RSS feed

 
maddy sidhan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I'm able to create a file and read its contents, but when I rename that file between its creation and reading, I get a "java.io.FileNotFoundException".

Here it goes:

1. Creating a new file:


2. Renaming the file:


3. Read file:


I get java.io.FileNotFoundException at line 02 above (BufferedReader br = new BufferedReader(new FileReader(newFile1));)

It seems File reference (newFile1) is still referring to original file that was created (namely, newDir/newFile1.java), whereas the file has been renamed.
As mentioned before, if I remove renaming code, I'm able to read file OK.
Any ideas if this renaming is not allowed in Java or is a bug?

Many Thanks.
 
maddy sidhan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, pressed "Resolved" button by mistake. Not resolved.
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot change the abstract path of a File object since it's instances are immutable (as stated in the API). Hence the newFile1 object always contains original path you used to create a file, not the modified one.

Note that renameTo method returns a boolean which indicates if the renaming succeeded so you can use it as an indicator. However, if you want to read new file, you need to specify it's new path.
 
maddy sidhan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Makes sense. Many thanks.
 
maddy sidhan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Makes sense. Many thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!