检查文件是否存在? file.exists() return 始终为假

Check if file exists or not? file.exists() return always false

我在检查文件是否存在时遇到问题这是我的简单代码:

File myfile = new File ("SecretFile");

            if(myfile.exists(){

                TextView mytxt = (TextView)findViewById(R.id.textView);
                mytxt.setText("Loaded successfully");

            }
            else{
                try {
                    myfile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                TextView mytxt = (TextView)findViewById(R.id.textView);
                mytxt.setText("Not loaded,reboot the application");
            }

我正在做一个简单的游戏,我需要检查第一个应用程序 运行,因为当应用程序 运行 加载文件中的所有变量时,但在第一个 运行没有文件,所以应用程序崩溃了。 我还有一个问题,文件 "SecretFile" 位于何处? 如何在 Android/data/com.mypackage.myapp/SecretFile 中创建文件?

File myfile = new File ("SecretFile");

该声明对 Android 没有任何意义。

I also have another question the File "SecretFile" where is located?

无处可去。欢迎您将 SecretFile 存储在 internal storage or external storage 上,但您必须创建指向这些位置的 File 对象(例如 File myfile = new File(getFilesDir(), "SecretFile");)。

How can I create a file inside Android/data/com.mypackage.myapp/SecretFile ?

你不能。最接近的匹配是 use getExternalFilesDir(null),我在上面的代码片段中有 getFilesDir(),这会将您的文件放在外部存储的 Android/data/com.mypackage.myapp/files/SecretFile 中。另外,正如 Der Golem 指出的那样,您需要 WRITE_EXTERNAL_STORAGE 权限才能进入 API 级别 4 到 18。

在 android 中创建文件时,您需要添加创建文件的路径。如果您不能满足其要求,则不会创建文件。

这就是为什么你的 return 数据总是错误的原因。

可以帮到你。