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

时间:2015-02-18 06:37:48

标签: android android-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();
}

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

4 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

您只需要创建一个File的对象,并将您的路径传递给File对象,然后使用方法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();
}

答案 2 :(得分:0)

这样可以解决问题:

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

答案 3 :(得分:0)

试试这个

考虑到您正在使用这样的视频观看

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

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