9

What's the best/easiest way to rename a file in the application's internal storage? I find it a bit strange that there is a Context.deleteFile() method, but no "move" or "rename" function. Do I have to go all the way through saving the file's contents, deleting it, creating a new one and then copying the contents into that one? Or is there a way to copy a file over an existing file?

Update (Aug. 30, 2012):

As per the suggested solution below, which I cannot get to work:

  • I have a file called shoppinglists.csv
  • Then I create a new file called shoppinglists.tmp, and copy the contents from shoppinglists.csv AND some new entries into that. The shoppinglist.tmp file is then a new version of the shoppinglists.csv file
  • Then I delete the old shoppinglists.csv file
  • Then I need to rename the shoppinglists.tmp file to shoppinglists.csv

I tried this:

ctx.deleteFile("shoppinglists.csv");           <--- delete the old file
File oldfile = new File("shoppinglists.tmp");
File newfile = new File("shoppinglists.csv");
oldfile.renameTo(newfile);

However, this doesn't work. After deleteFile(), nothing more happens, and I'm left with the new shoppinglists.tmp file.

What am I missing?

NB: There are no errors or anything in LogCat.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Check this solution http://stackoverflow.com/questions/2896733/how-to-rename-filename-in-sdcard-with-android-application – Vishal Pawar Aug 29 '12 at 15:28

4 Answers4

8

Instead of using a raw File constructor, use the method getFileStreamPath provided by the Context. That is to say, do:

File oldfile = ctx.getFileStreamPath("shoppinglists.tmp");
File newfile = ctx.getFileStreamPath("shoppinglists.csv");
oldfile.renameTo(newfile);
JulianSymes
  • 2,135
  • 22
  • 24
  • The problem is presumably that `new File("fred")` refers to a name relative to the program's current directory, which is probably not, and certainly not guaranteed to be, the directory in which internal files are stored. – JulianSymes Nov 26 '12 at 13:59
  • Its not working with internal storage files – Shaahul Dec 04 '20 at 01:17
0

renameTO() doesn't work in my environment (Eclipse Indigo, AVD with android version 2.3). The solution is to skip the temporary file method alltogeher, since it doesn't seem to be possible to solve in any reasonable time frame.

0

I think we cannot use File.renameTo() method in Internal Storage environment. Renaming a file in this environment, can do: - Copy content of the old file to new file. - Delete old file.

TNLong
  • 1
  • 1
0
File file = new File("your old file/folder name");
File file2 = new File("your new file/folder name");
boolean success = file.renameTo(file2);
Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81