Ziad H.
Ziad H.

Reputation: 699

Copying files in android from uri to app's private folder

My app should take an image from gallery and put it into app data directory. My implementation was that I tried sharing an image from gallery directly into the app and using its uri to copy it from its source position to the android app directory.

After receiving the image URI:

copyFile(new File(mImageUri.getPath()), getFilesDir());

The copyFile method:

public void copy(File src, File dst) throws IOException {
         try (InputStream in = new FileInputStream(src)) {
             try (OutputStream out = new FileOutputStream(dst)) {
                 // Transfer bytes from in to out
                 byte[] buf = new byte[1024];
                 int len;
                 while ((len = in.read(buf)) > 0) {
                     out.write(buf, 0, len);
                 }
             }
         }
     }

The problem is that I get a FileNotFound exception, how can I fix that?

Upvotes: 1

Views: 1407

Answers (1)

Oleg Ukhanyov
Oleg Ukhanyov

Reputation: 21

First, use this get a file:

private fun openFile() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"
    }

    fileRequest.launch(intent)
}

fileRequest :

    private val fileRequest =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { resultData ->
        resultData?.data?.also { data ->
            val myFile = File(
                requireContext().filesDir,
                "test_file.pdf"
            ) // filesDir - Your app's ordinary, persistent files reside directory
            val inputStream: InputStream =
                requireActivity().contentResolver.openInputStream(data.data!!)!!
            val outputStream: OutputStream = FileOutputStream(myFile)
            val buf = ByteArray(1024)
            var len: Int
            while (inputStream.read(buf).also { len = it } > 0) {
                outputStream.write(buf, 0, len)
            }
            outputStream.close()
            inputStream.close()
        }
    }

Change line type = "application/pdf" to specify, what king of files do you want to copy

Also, fileRequest is declared in fragment scope (If you don't like it, old "startActivityForResult", it will work just fine.

Also also, openInputStream(data.data!!), data.data!! is uri of picked file

Upvotes: 1

Related Questions