-1

I want to copy a file from external storage to my folder that exists in external storage. I choose the file using

  Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
  chooseFile.setType("*/*");
  chooseFile = Intent.createChooser(chooseFile, "Choose a file");
  startActivityForResult(chooseFile, 1);

and try to copy this file in activityResult using:

   Uri selected = data.getData();
   String[] filePathColumn = { MediaStore.Files.FileColumns.DATA};

   Cursor cursor = getContentResolver().query(selected,
                        filePathColumn, null, null, null);
   cursor.moveToFirst();

   int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
   String FilePath = cursor.getString(columnIndex);
   cursor.close();

   FileInputStream fis = new FileInputStream(FilePath);
   String outFileName = Environment.getExternalStorageDirectory() + "/MyPath/" + "MyFileName";


   OutputStream output = new FileOutputStream(outFileName);


   byte[] buffer = new byte[1024];
   int length;
   while ((length = fis.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
   }


   output.flush();
   output.close();
   fis.close();

but something is wrong cause I get null in FilePath.How can I do this?

  • Use `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. Note that you do not have access to `Environment.getExternalStorageDirectory()` on Android 10 (by default) and Android R+ (for all apps). – CommonsWare Oct 01 '19 at 10:40
  • Hello @CommonsWare, I'm kind of having same situation, I've used openInputStream() but still, I'm stuck, Please check my question about it: https://stackoverflow.com/questions/58539583/android-q-get-image-from-gallery-and-process-it – Parag Pawar Oct 24 '19 at 10:45

1 Answers1

0

Just try this code,

private void copyFile(String inputPath, String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath); 
        if (!dir.exists())
        {
            dir.mkdirs();
        }


        in = new FileInputStream(inputPath + inputFile);        
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

            // write the output file (You have now copied the file)
            out.flush();
        out.close();
        out = null;        

    }  catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    }
            catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}

set the correct permission in the manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Akhil
  • 379
  • 4
  • 14