I want to check whether a given file exists in android sd card. I am trying it out with creating a file using the absolute path and checking with file.exists()
but its not working. The URL for the file is "file:///mnt/sdcard/book1/page2.html"
and the file does exist. But somehow file.exists()
isn't showing the same.
Asked
Active
Viewed 3.2k times
7
-
Possible duplicate of [Check if file exists on SD card on Android](https://stackoverflow.com/questions/7697650/check-if-file-exists-on-sd-card-on-android) – Adriana Hernández Aug 24 '17 at 20:44
7 Answers
51
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html");
if(myFile.exists()){
...
}
This should work.

Adam Monos
- 4,287
- 1
- 23
- 25
7
Try like this:
File file = new File(Environment.getExternalStorageDirectory() + "/book1/page2.html");
if (file.exists()) {
/*...*/
}
Also make sure you have:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
in your manifest file.

Caner
- 57,267
- 35
- 174
- 180
1
You can check as follows:
File file = new File(getExternalCacheDirectory(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}

Richard Harrison
- 19,247
- 4
- 40
- 67

Aamirkhan
- 5,746
- 10
- 47
- 74
0
File logFile = new File(
android.os.Environment.getExternalStorageDirectory()
+ "/book1/", "page2.tml");
if (logFile.exists())
System.out.println("file exists");
else
System.out.println("file does not exist

sunil
- 6,444
- 1
- 32
- 44
0
Do something like this :
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "your/file/path");
if(yourFile.exists())
{
}

Vipul Purohit
- 9,807
- 6
- 53
- 76
0
String filepath = getFilesDir().getAbsolutePath();
String FileName = "Yourfilename" ;
File FileMain = new File(filepath, FileName);
if (FileMain.exists()){
do somthing here
}else{}

Ankitkumar Makwana
- 3,475
- 3
- 19
- 45
0
File file = new File(path+filename);
if (file.exists())
{
//Do something
}
checked, this will work

mickmister
- 75
- 10

Arunprabu
- 11
- 3