4

I am trying to check if a file exists in my user's Download directory.

File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),imageName);
if(imageFile.exists())
  // Do something
else
  // Do something else

I have gotten the contents of the directory

File did = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
File files[] = dir.listFiles();

In the debugger:

imageFile.path = "/storage/emulated/0/Download/floorplan_lobby.png"

And

files[12].path = "/storage/emulated/0/Download/floorplan_lobby.png"

But imageFile.exists() returns false. Why?

It shouldn't matter, but I'm using a Samsung Galaxy Note.

4b0
  • 21,981
  • 30
  • 95
  • 142
Dan Eckhart
  • 245
  • 2
  • 8

1 Answers1

0

Check

  1. Manifest permissions
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. Use file provider to create and access file
    <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="your_package.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_list" />
        </provider>
  1. file_list content:
    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path
            name="external"
            path="." />
        <external-files-path
            name="external_files"
            path="." />
        <cache-path
            name="cache"
            path="." />
        <external-cache-path
            name="external_cache"
            path="." />
        <files-path
            name="files"
            path="." />
    </paths>
  1. Keep your filename short
Mainong
  • 43
  • 4