android, How to rename a file?
In your code:
Shouldn't it be :
File from = new File(directory, currentFileName);
instead of
File from = new File(directory, "currentFileName");
For safety,
Use the File.renameTo() . But check for directory existence before renaming it!
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exists())
from.renameTo(to);
}
Refer: http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29
The problem is in this line,
File from = new File(directory, "currentFileName");
Here currentFileName
is actually a String you dont have to use "
try it this way,
File from = new File(directory, currentFileName );
^ ^ //You dont need quotes
Use this method to rename a file. The file from
will be renamed to to
.
private boolean rename(File from, File to) {
return from.getParentFile().exists() && from.exists() && from.renameTo(to);
}
Example code:
public class MainActivity extends Activity {
private static final String TAG = "YOUR_TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File currentFile = new File("/sdcard/currentFile.txt");
File newFile = new File("/sdcard/newFile.txt");
if (rename(currentFile, newFile)) {
//Success
Log.i(TAG, "Success");
} else {
//Fail
Log.i(TAG, "Fail");
}
}
private boolean rename(File from, File to) {
return from.getParentFile().exists() && from.exists() && from.renameTo(to);
}
}