10

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:

FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);

How can I check whether this file exists?

laalto
  • 150,114
  • 66
  • 286
  • 303
androiddevs78
  • 141
  • 2
  • 2
  • 9

6 Answers6

50

This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():

File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
  //Do action
}
Ljdawson
  • 12,091
  • 11
  • 45
  • 60
  • 4
    please note: getExternalCacheDir() may not be what you want. If you are wanting a directory on sd that will be cleared up after app is uninstalled (e.g. a 'cache' dir), use getExternalCacheDir(). But if you want the top level dir of the sd card, then you may be better using: File sdDir = new File(Environment.getExternalStorageDirectory().getPath()); – DEzra Aug 21 '14 at 12:49
2

*Using this you can check the file is present or not in sdcard *

File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
 {

}
Neelaganda Moorthy
  • 1,014
  • 7
  • 6
2

See this file System in android : Working with SDCard’s filesystem in Android

you just check

if(file.exists()){
//
}
prayagupa
  • 30,204
  • 14
  • 155
  • 192
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
0

check IF condition with Boolean type like

File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}
Arunprabu
  • 11
  • 3
0

You have to create a file, and set it to be the required file, and check if it exists.

String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}

Have Fun!

RE6
  • 2,684
  • 4
  • 31
  • 57
  • It's best not to use the hard coded reference to the SD card, see my earlier answer for a better way to access the external storage. – Ljdawson Oct 08 '11 at 15:10
0

The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.

Also, make sure you have permission to access the SD card.

Community
  • 1
  • 1
Zach Rattner
  • 20,745
  • 9
  • 59
  • 82