Error File.renameTo ()

I have an eclipse plugin jface application. The stream writes the file through BufferedWriter. At the end of the recording, I close the buffer after that, I try to rename the file.

But sometimes the file is not renamed!

I tried adding a few Thread.Sleep (BIG_NUMBER) between two attempts, this did not help.

It looks like the file is getting some kind of lock. (when I kill jvm, I can rename the file).

Is there something I can do?

OS: Windows XP, Windows 7 JAVA Version: 1.5

+7
source share
5 answers

File.RenameTo () is platform dependent and relies on several conditions that must be met in order to successfully rename a file, it is better to use

Path source = currentFile.toPath(); try { Files.move(source, source.resolveSibling(formattedName)); } catch (IOException e) { e.printStackTrace(); } 

More details here .

From javadocs:

Many aspects of the behavior of this method are inherently platform-dependent: the renaming operation may not be a file from one file system to another, it may not be atomic, or it may not work if a file with the target destination name already exists. You always need to check the return value to make sure that the rename operation is successful.

Note that the Files class defines a move method for moving or renaming a file, regardless of platform.

+13
source

For File.renameTo() to work, the file must in some way be writable by external applications.

0
source

You can also do something like below:

 File o=new File("oldFile.txt"); File n=new File("newFile.txt"); n.delete(); o.renameTo(n); 

n.delete() : We need to delete the file (new.txt), if it exists.

o.rename(n) : so that the file (old.txt) is renamed to new.txt

How to find out why renameTo () failed?

Reliable alternative to File.renameTo () on Windows?

http://www.bigsoft.co.uk/blog/index.php/2010/02/02/file-renameto-always-fails-on-windows

0
source

We had problems with Windows 7 with UAC and unexpected file permissions. File#canWrite will return true even if any attempts to perform file input / output fail.

  • Make sure the file you are trying to rename actually exists
  • Make sure the location where you are trying to write the file (or rename the file) is available. We write a simple text file to the location, check if it exists and that the content is correct (we are paranoid) before we try to perform further input-output operations.
0
source

This works great for me. Renaming is done using two steps, but remember to set permissions in manifest.xml with:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> public boolean RenameFile(String from, String to) { to.replace(" ", ""); // clear all spaces within file name File oldfile = new File(from); File newfile = new File(to); File tempfile = new File(to + ".tmp"); // add extension .tmp oldfile.renameTo(tempfile); return (tempfile.renameTo(newfile)); } 
0
source

All Articles