Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

renameTo doesn't work on SWING  RSS feed

 
Ethan Chen
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,
I have a probleme to swap two .JPG file names by using renameTo().
here is the code:
File fileSource = new File(strSelectedBaseURI,strSource); //existing file
File fileTarget = new File(strSelectedBaseURI,strTarget); //existing file
File fileTemp1= new File(strSelectedBaseURI,"temp1.jpg");

fileSource.renameTo(fileTemp1);
fileTarget.renameTo(fileSource);
fileTemp1.renameTo(fileTarget);
.....
after doing this, the files in the disk(file syatem is changed), however, it doesn't show the correct result when the SWING reload those two files uging
new ImageIcon(strSelectedBaseURI,strSource) and
new ImageIcon(strSelectedBaseURI,strTarget).
can anyone help me out?
Thanks in advance
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, one thing about renameTo() is that you should always check its return value to see if it succeeded or not. The API is rather poorly designed; it's too easy to fail without realizing it. I usualy wrap it with a method like this:

You can add code to check for common reasons for failure, suce as whether the src file exists, whether you have write access to the src file, whether the dest file already exists, whether the parent directory of the dest file exists. Unfortunately the method may still fail with no explanation (other than "false"). Often this is because some other process or thread has opened the file you're trying to rename; Java doesn't seem to have a good way to find out if this is the case. Just make sure that you close all streams you open (preferably using a finally block).
However in this case, it seems that the rename does work, and your problem is with the ImageIcon. Take a look at the API for ImageIcon. Which constructor are you using? It looks like it's new ImageIcon(String, String). Look at the description for what the second parameter means - it's jus the description. It has no effect on which file gets loaded. That's your problem here. You probably want to use the new ImageIcon(String) constructor instead. Forget about the URI at this point - just provide the names of the files. You may want to use the previously constructed File objects to get an absolute path for each file, since it loooks like the base strSource and strTarget may not have all the info to locate the file.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!