• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Issue reading a file after renaming it.

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, pressed "Resolved" button by mistake. Not resolved.
 
Bartender
Posts: 825
5
Python Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Makes sense. Many thanks.
 
maddy sidhan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Makes sense. Many thanks.
 
Oh sure, it's a tiny ad, but under the right circumstances, it gets bigger.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic