Search code examples
androidfileoutputstreamandroid-10.0

File operations in android Q beta


1)Target set to Android Q with android.permission.WRITE_EXTERNAL_STORAGE

2) use getExternalStorageDirectoryor getExternalStoragePublicDirectoryand FileOutputStream(file)saving file throws

java.io.FileNotFoundException: /storage/emulated/0/myfolder/mytext.txt open failed: ENOENT (No such file or directory)

3) use getExternalFilesDirapi and saving is success but wont show up even after MediaScannerConnection.scanFile.

     /storage/emulated/0/Android/data/my.com.ui/files/Download/myfolder/mytext.txt

What is best way to copy file from internal memory to SDCARD in android Q and refresh.


Solution

  • In Android API 29 and above you can use the below code to store files, images and videos to external storage.

    //First, if your picking your file using "android.media.action.IMAGE_CAPTURE" then store that file in applications private Path(getExternalFilesDir()) as below.

    File destination = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
    

    //Then use content provider to get access to Media-store as below.

     ContentValues values = new ContentValues(); 
     values.put(MediaStore.Images.Media.TITLE, fileName); 
     values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
    

    //if you want specific mime type, specify your mime type here. otherwise leave it blank, it will take default file mime type

    values.put(MediaStore.Images.Media.MIME_TYPE, "MimeType"); 
    values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000); 
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); 
    values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + "path"); // specify 
     storage path
    

    // insert to media-store using content provider, it will return URI.

    Uri uri = cxt.getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); 
    

    //Use that URI to open the file.

    ParcelFileDescriptor descriptor = context.getContentResolver().openFileDescriptor(uri,"w"); //"w" specify's write mode
    FileDescriptor fileDescriptor = descriptor.getFileDescriptor();
    

    // read file from private path.

    InputStream dataInputStream = cxt.openFileInput(privatePath_file_path);
    

    //write file into out file-stream.

     OutputStream output = new FileOutputStream(fileDescriptor);
     byte[] buf = new byte[1024];
     int bytesRead;
     while ((bytesRead = dataInputStream.read(buf)) > 0) 
     {
      output.write(buf, 0, bytesRead);
     }
     datanputStream.close();
     output.close();
    }