8

I have a temp file that is made for creating an image from a cropping library and I can see the file in Device File Explorer but when I try to open the file I get this error:

java.io.FileNotFoundException: file:/data/user/0/com.example.demo/cache/.tmp/cropped1651879842159823361.png: open failed: ENOENT (No such file or directory)

This is how that file is created:

val croppedImageFile = File.createTempFile("cropped", ".png", viewModel.tempPath)
val destinationUri = Uri.fromFile(croppedImageFile)

viewModel.tempPath is just the following:

viewModel.tempPath = "${this.cacheDir}/.tmp"

I can see that file got created and is valid, but when I try to access it, it claims it doesn't exists. I simply open the file by doing File(uri.toString()). in the view model

I'm not sure what is wrong and why it can't find the file. If this matters, I'm using an emulator that has google play and it's Android 11.

6
  • Post the code actually opening it. May 31, 2022 at 19:45
  • I did, it's just File(uri.toString())
    – Eman
    May 31, 2022 at 19:47
  • try adding this android:requestLegacyExternalStorage="true" in AndroidManifest.xml application tag.
    – Abu bakar
    May 31, 2022 at 19:54
  • 1
    I tried that and still getting the same error.
    – Eman
    May 31, 2022 at 19:57
  • 1
    @Eman Creating a file object doesn't cause an FileNotFoundException because it doesn't open the file- it just creates a reference to it. It's entirely legitimate to create a File to a path that doesn't exist. You may be passing it somewhere else that is actually opening it. May 31, 2022 at 20:02

1 Answer 1

2

You need to open the file using new File(uri.getPath()).

uri.toString() returns the URI as a string, that means "file://path/to/file" which is not a valid path.

1
  • that looks to be it, thanks so much
    – Eman
    May 31, 2022 at 21:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.