不能检查SD卡上的文件存在卡上、存在、文件、SD

2023-09-13 23:58:08 作者:旧心愿.

我试图做一个简单的检查,如果该文件存在。我看到了类似的问题在这里,但他们并没有帮助。当我运行我的应用程序,该应用程序崩溃,我得到的消息很遗憾,fileCheck1已经停止。我在仿真器和智能手机得到这个错误两种。

I'm trying to make a simple check if the file exist. I saw similar questions here, but they didn't help. When I run my application, the app crashes and I got message "Unfortunatelly, fileCheck1 has stopped". I got this error both on emulator and smartphone.

我的code:

package com.example.fileCheck1;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

import java.io.File;

public class MyActivity extends Activity {

    TextView msgText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        msgText = (TextView) findViewById(R.id.textView);
        String Path = Environment.getExternalStorageDirectory().getPath()+"/ping.xml";
        File file = getBaseContext().getFileStreamPath(Path);
        if(file.exists()){
            msgText.setText("Found");
        }
        if(!file.exists()){
            msgText.setText("Not Found");
        }
    }
}

在我的清单这样的权限:

In my Manifest such permissions:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

在此先感谢。

Thanks in advance.

推荐答案

我认为这个问题是在这里:

I think that problem is here:

getBaseContext()

在那里被分配为 NULL 。你真的不需要这行。你可以简单地实现自己的目标,以

where it is assigned to NULL. You really don't need this line. You can simply achieve your goal with

String path = Environment.getExternalStorageDirectory().getPath() + "/ping.xml";
File f = new File(path);
if (f.exists()) {
   // do your stuff
}
else {
  // do your stuff
}

更新:

如果你或其他人有三星Galaxy S3,请关注@ Raghunandan的答案,因为在这种情况下 getExternalStorageDirectory()返回内部存储器。

Update:

If you or someone else have Samsung Galaxy S3, please follow @Raghunandan's answer because in this case getExternalStorageDirectory() returns internal memory.