如何检查外部存储中是否存在文件?

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

如何查看外部存储中是否存在文件?

我想播放来自外部存储的视频,如果该文件存在于其中,否则从服务器下载。 我试过了

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();
}

以上代码的问题是它总是从服务器播放视频。

我也试过了-

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();
}

问题是它总是从外部存储播放视频。

您可以通过以下代码检查文件是否存在..

File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html");

if(myFile.exists()){
    ...
}

你只需要创建一个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();
}

这样做就可以了:

File file = new File(sdcardPath + "myvideofile.mp4" );
if (file.exists()) {
 //Do action
}

试试这个

考虑到您正在使用这样的视频视图 </p> <pre><code>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);