我想在Sdcard制作目录,我确实遵循:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
。public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/";
然后它返回
/storage/emulated/0/Hello_World
(调试时获取)。接下来,我运行此代码:
File file = new File(Constants.ROOT_PATH);
int i = 0;
while (!file.isDirectory() && !file.mkdirs()) {
file.mkdirs();
Log.e("mkdirs", "" + i++);
}
我也尝试了mkdirs()
和mkdir()
,但它在logcat(Log.e("mkdirs", "" + i++);
)中显示无限循环。有时它有效,但有时不行。
谢谢你的帮助!
Update
:我尝试了一些设备的代码:Nexus4,nexus7,Vega Iron,Genymotion,LG G Pro,然后Vega Iron就像预期的那样工作。 ?? !!?!?
答案 0 :(得分:2)
尝试这样做会在sd card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_world");
myDir.mkdirs();
如果您想检查该文件是否存在,请使用此代码
File file = new File (myDir, file_name);
if (file.exists ())
// file exist
else
// file not exist
有关参考,请参阅此答案Android saving file to external storage
答案 1 :(得分:1)
该错误是由&&
while (!file.isDirectory() && !file.mkdirs())
引起的,while (!file.isDirectory() || !file.mkdirs())
应该是if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null)
{
String externalStoragePath = externalStorage.getAbsolutePath();
File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$
if (soundPathDir.isDirectory() || soundPathDir.mkdirs())
{
String soundPath = soundPathDir.getAbsolutePath() + File.separator;
if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$
}
}
}
。您还应该检查介质是否已安装。
{{1}}
从我的一个项目剪切并粘贴。
答案 2 :(得分:1)
谢谢大家,最后我发现了问题。问题出在while()
循环中,我替换为
如果 (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) &安培;&安培; !file.isDirectory()){
file.mkdirs();
}
答案 3 :(得分:0)
使用Environment.getExternalStorageDirectory().getAbsolutePath()
如下...
public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Hello_World/";
在创建目录之前检查是否已安装SDCard,如下所示....
File file = new File(Constants.ROOT_PATH);
int i = 0;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if(!file.exists()) {
file.mkdir();
}
}