5

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.

Eman
  • 1,093
  • 2
  • 26
  • 49
  • Post the code actually opening it. – Gabe Sechan May 31 '22 at 19:45
  • I did, it's just File(uri.toString()) – Eman May 31 '22 at 19:47
  • try adding this `android:requestLegacyExternalStorage="true"` in `AndroidManifest.xml` application tag. – Abu bakar May 31 '22 at 19:54
  • 1
    I tried that and still getting the same error. – Eman May 31 '22 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. – Gabe Sechan May 31 '22 at 20:02
  • yup, sorry, on the api call I'm using it on I'm opening it by doing this: file.readBytes() – Eman May 31 '22 at 20:04

1 Answers1

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.

Abror Esonaliev
  • 11,797
  • 2
  • 23
  • 20
yuvalpo
  • 51
  • 1
  • 4