1

How to check whether a file is present in external storage?

I want to play a video from external storage if that file is present in it otherwise download it from server. I tried

if ((Environment.getExternalStorageDirectory().getPath().contains(mVideo.getCaption() + ".mp4"))) {
    videoPath = Environment.getExternalStorageDirectory().getPath() + "/" + mVideo.getCaption() + ".mp4";
    Toast.makeText(getActivity(), "Playing from External storage" + videoPath, Toast.LENGTH_LONG).show();
} else {
    videoPath = URLs.VIDEO_URL.replace("<fixme>", mVideo.getId());
    Toast.makeText(getActivity(), "Playing from Server" + videoPath, Toast.LENGTH_LONG).show();
}

The problem with above code is that it is always playing video from server.

I also tried-

if ((Environment.getExternalStorageDirectory().getPath() + "/" + mVideo.getCaption() + ".mp4")!=null) {
    videoPath = Environment.getExternalStorageDirectory().getPath() + "/" + mVideo.getCaption() + ".mp4";
    Toast.makeText(getActivity(), "Playing from External storage" + videoPath, Toast.LENGTH_LONG).show();
} else {
    videoPath = URLs.VIDEO_URL.replace("<fixme>", mVideo.getId());
    Toast.makeText(getActivity(), "Playing from Server" + videoPath, Toast.LENGTH_LONG).show();
}

Problem with this is that it is always playing video from external storage.

SilentKiller
  • 6,944
  • 6
  • 40
  • 75
Android Developer
  • 9,157
  • 18
  • 82
  • 139

3 Answers3

0

You just need to create an object of File and pass your path to the File object and just use method exists().

String mFilePath = Environment.getExternalStorageDirectory().getPath().contains(mVideo.getCaption() + ".mp4");
File mFile = new File(mFilePath);
if (mFile !=null && mFile.exists()) {
    Toast.makeText(getActivity(), "Playing from External storage" + mFilePath, Toast.LENGTH_LONG).show();
}
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
0

This would do the trick:

File file = new File(sdcardPath + "myvideofile.mp4" );
if (file.exists()) {
 //Do action
}
varun bhardwaj
  • 1,522
  • 13
  • 24
0

Try this

Considering you are using a video view like this

VideoView videoView = (VideoView) findViewById(R.id.videoView);
.
.
.
Uri videoUri;
File videoFile =new File("your_file_path");
if(videoFile.exists()){
   videoUri =Uri.fromFile(videoFile);
}else{
   videoUri =Uri.parse(videoUrl));
}

videoView.setVideoURI(videoUri);

Prateek Thakur
  • 179
  • 1
  • 5