Home > Software design >  How to move files from internal storage to app directory?
How to move files from internal storage to app directory?

Time:08-12

I am making a app that store files get files from Internal Storage and lock those files in app directory /data/data/[package_name]/videos/.

I try to move files files through this method but it is not working for me.

source.renameTo(new File("data/data/"   this.getPackageName()   "/files/videos/"   video_title));

TRIED BEFORE

  • I tried this source.renameTo(new File("/storage/emulated/0/" this.getPackageName() video_title));. This worked and move file from soure to /storage/emulated/0/.
  • I also checked this directory exisits. Directory photo

PROBLEM

  • Problem is file is not moving from storage to app directory.

This is the actual function I am using to move file.

private boolean moveFile(File source, File destination) {
        boolean isDirectoryMade = false;
        
        // creates directory if not exists
        if (!destination.getParentFile().isDirectory()){
            File parent = destination.getParentFile();
            isDirectoryMade = parent.mkdirs();
        }
        
        // rename or move file.
        boolean isFileRenamed = source.renameTo(destination);

        return isDirectoryMade && isFileRenamed;
    }

CodePudding user response:

First, you'll have to copy that file to the app directory, reading the file using Storage Access Framework.

Then, still using SAF, you'll have to ask the user for delete the original one.

For both steps, Android now needs you to ask the user for accessing public directories, specifying if you read the file (the user will have to select the file manually) and delete it.

To ask the user for Document read, you'll have to use the following :

val selectFileRequest = registerForActivityResult(OpenDocument()) {
      result: Uri? -> 
            //Your code to copy the file here, the provided Uri is the selected file's

            //Then you can delete the file with the following:
            if(result != null)
            {
                //DocumentFile.fromSingleUri(this, result)?.delete()
                              //or
                //DocumentsContract.deleteDocument(getContentResolver(), result);
            }
}

Don't forget to add the needed permissions in your Manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>

In the end, just call the following in your code:

selectFileRequest.launch(
        arrayOf(
            //Any Mime type you want to target, like the followings :
            "application/pdf",
            "image/*",
            "text/*"
        )
    )
  • Related