简体   繁体   English

目录中存在调用总是在android中返回false

[英]calling exists on directory always return false in android

I am trying to create a directory in internal storage for my app. 我正在尝试为我的应用程序在内部存储中创建目录。 Following is the code I am using to check if the directory exists or not. 以下是我用来检查目录是否存在的代码。 If the directory already exists, it is returned; 如果目录已经存在,则返回它; else, the directory is created and returned. 否则,目录创建并返回。 But even in the subsequent calls to the method, the exists() call on the directory always return false. 但是,即使在随后的方法调用中,目录上的exist()调用也始终返回false。 What is the reason? 是什么原因? Thanks 谢谢

public File getMessageVoiceDirectory() {
    File messageVoiceDirectory = this.myContext.getDir("Voice",Context.MODE_PRIVATE);


    if (messageVoiceDirectory.exists() == false) {
        messageVoiceDirectory.mkdirs();
    }


    return messageVoiceDirectory;
}

First off, switch your condition to 首先,将您的条件切换为

if (!messageVoiceDirectory.exists()) {
    boolean actuallyCreated = messageVoiceDirectory.mkdirs();
    if (!actuallyCreated){
       Log.e("Activity", "Woah... the mkdirs command got called, but was not successful. We need to investigate.");
    }
}

Next, you need to check the return value of mkdirs . 接下来,您需要检查mkdirs的返回值。 Presumably the directory isn't being created. 大概没有创建目录。 This could happen if you don't have the correct permissions. 如果您没有正确的权限,则可能会发生这种情况。

You can try this one. 你可以试试这个。 It will work 会工作的

 File path = new File(this.getFilesDir(), "DirectoryName");
     if (!path.exists()) {
         path.mkdirs();
         Toast.makeText(this,"Created",Toast.LENGTH_LONG).show();
     }
     else
         Toast.makeText(this,"Already Exist",Toast.LENGTH_LONG).show();

When you exactly call getMessageVoiceDirectory() , ensure that you call inside onCreate(), 当您完全调用getMessageVoiceDirectory() ,请确保在onCreate()内部调用,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM