I have a file at location a/b/c.txt . I want to move this file to location d/e/f.txt .I want to rename the folder/directory a to d ,b to e and file c.txt to f.txt .How to do this in android?
public void moveFile(View view) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "a" + File.separator + "b" + File.separator + "c.txt");
if (file.exists()) {
boolean res = file.renameTo(new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + File.separator + "d" + File.separator + "e" + File.separator + "f.txt"));
Toast.makeText(MainActivity.this, String.valueOf(res), Toast.LENGTH_SHORT).show();
}
}
You are very much on the right track when you say “I want to rename the folder/directory a to d ,b to e and file c.txt to f.txt .” You just have to rename one directory at a time and the file itself separately:
String externalStorageDirAbsPath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(externalStorageDirAbsPath + File.separator + "a" + File.separator + "b" + File.separator + "c.txt");
if (file.exists()) {
// first rename a to d
boolean res = new File(externalStorageDirAbsPath + File.separator + "a")
.renameTo(new File(externalStorageDirAbsPath + File.separator + "d"));
if (res) {
// rename b to e
res = new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "b")
.renameTo(new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e"));
if (res) {
// rename c.txt to f.txt
res = new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e" + File.separator + "c.txt")
.renameTo(new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e" + File.separator + "f.txt"));
}
}
Toast.makeText(MainActivity.this, String.valueOf(res), Toast.LENGTH_SHORT).show();
}
I have tested the central part of the code on Mac OS X. I have not tested on Android. If there’s a typo in the hand translation back to Android code, I hope you’ll be able to figure it out.
Instead of the File
class you may want to look into the newer java.nio.file
package, the Path
class may give you a little convenience here, but I think you would still have to rename one directory at a time and the file separately, just as here.