android, How to rename a file?

前端 未结 9 2122
Happy的楠姐
Happy的楠姐 2020-11-28 09:58

In my application, I need to record video. Before start of recording in I\'m assigning a name and directory to it. After recording is finished user has ability to rename his

9条回答
  •  半阙折子戏
    2020-11-28 10:17

    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);
        }
    }
    

提交回复
热议问题