use*_*782 4 directory android directory-structure file
我正在尝试检查 SD 卡上是否存在子目录结构;
如果不是,则创建一个新的。
这当然是在我的代码验证 SD 卡已安装并准备好之后。
我创建了有效的代码,并成功地在我的手机的 SD 卡上创建了结构,所以我知道我的代码很好。然后我去睡觉了。第二天,我将工作代码从我的测试区域移动到我的工作区域,现在它不起作用了!!:-(我什至把它移回测试区,但仍然没有工作!!
我猜晚上 Android Gremlins 做了一些破坏代码的事情!!
所以......要么Android Gremlins做了什么,要么(这是一个很长的镜头)当我移动代码时我可能忘记了一些东西。有没有人有任何 Gremlin 驱虫剂?
我很确定有效并实际创建了我现在可以在手机上看到的结构的代码是这样的:
String strPathName = m_Context.getExternalFilesDir (null) .toString ();
// This DOES give the Correct Path on the SD Card
File dir;
dir = new File (m_Context.getExternalFilesDir (null) + "/MyDirectory");
dir = new File (m_Context.getExternalFilesDir (null) + "/MyDirectory/SubDir");
dir = new File (m_Context.getExternalFilesDir (null) + "/MyDirectory/SubDir/xxx");
Run Code Online (Sandbox Code Playgroud)
在我的手机上,我可以清楚地看到这个结构。现在还在那里!!
第二天,(即在 Android Gremlins 访问之后)我尝试将这个和其他代码从我的测试区域移动到不同的部分,之后,它不再创建结构。
File dir;
boolean bDirExists;
dir = new File (m_Context.getExternalFilesDir (null) + "/NewDirectory");
bDirExists = (dir.exists () && dir.isDirectory () ); // FALSE
dir = new File (m_Context.getExternalFilesDir (null) + "/NewDirectory/SubDir");
bDirExists = (dir.exists () && dir.isDirectory () ); // FALSE
bDirExists = dir.exists (); // FALSE
bDirExists = dir.isDirectory (); // FALSE
dir = new File (m_Context.getExternalFilesDir (null) + "/NewDirectory/SubDir/xxx");
bDirExists = (dir.exists () && dir.isDirectory () ); // FALSE
Run Code Online (Sandbox Code Playgroud)
如果…。我使用前一天使用的原始名称“/MyDirectory/SubDir/xxx”)
然后代码表明目录确实存在
dir = new File (m_Context.getExternalFilesDir (null) + "/MyDirectory");
bDirExists = (dir.exists () && dir.isDirectory () ); // TRUE
dir = new File (m_Context.getExternalFilesDir (null) + "/MyDirectory/SubDir");
bDirExists = (dir.exists () && dir.isDirectory () ); // TRUE
bDirExists = dir.exists (); // TRUE
bDirExists = dir.isDirectory (); // TRUE
Run Code Online (Sandbox Code Playgroud)
现在……我们都知道,程序员永远不会破坏他们的代码,也永远不会将错误引入“已知的工作代码”,所以……。一定是小精灵…… 对??
@ChuongPham 评论说我可能需要在 Manifest 文件中添加正确的权限。
由于代码 DID WORK,这意味着我确实已经启用了此权限。
但是,我决定删除此权限并查看它会抛出什么错误,我认为它不会在没有权限的情况下编译。然后我运行了代码并且没有抛出错误!!是的,它仍然不会创建一个新文件..
如果您使用m_Context.getExternalFilesDir("MyDirectory/SubDir")自定义目录,则会自动为您创建。在 API 19 或更高版本上测试...
也许您需要将此权限添加到您的 AndroidManifest.xml 文件中:
android.permission.WRITE_EXTERNAL_STORAGE
Run Code Online (Sandbox Code Playgroud)
另外,请阅读此处了解有关 API 19 及更高版本的注意事项。