我正在尝试通过应用程序在外部存储目录中创建文件夹和文件。
File f = new File("/storage/emulated/0", mFileName);
boolean isCreated = f.mkdir();
这总是成功的,并且isCreated为真,没有任何异常或警告并且创建了文件夹。
Environment.getExternalStorageDirectory()返回" / storage / emulated / 0"太
但是当我尝试在外部存储卡(可移动存储卡)中创建文件夹时如下:
File f = new File("/storage/6161-3165", mFileName);
boolean isCreated = f.mkdir();
始终f.mkdir()返回false并且未创建文件夹。 同时我可以在logcat中看到W / System.err:...如下:
**02-22 14:50:47.551 13536-13536/com.testapp.extsd W/System.err: mkdir failed: EACCES (Permission denied) : /storage/6161-3165/uyyyy**
我在清单文件中提到了WRITE_EXTERNAL_STORAGE权限。尚未创建静态文件夹。
我想知道如何在外部存储卡中创建文件夹和文件。
我的手机中的存储文件结构是:
shell@j7xelte:/storage $ ls -l
drwxrwx--x root sdcard_rw 2017-02-05 07:59 6161-3165
drwx--x--x root sdcard_rw 2016-01-01 17:34 emulated
drwxr-xr-x system system 2017-02-05 07:59 enc_emulated
drwxr-xr-x root root 2017-02-05 07:59 self
shell @ j7xelte:/ storage $
等待回复...
答案 0 :(得分:0)
首先,您必须为AndroidManifest添加一些权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
要在外部存储空间中创建文件夹,请调用此类
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
此外,对于Android&gt; 6,您必须调用运行时权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
获得结果
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
并检查
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic here
return true;
}
答案 1 :(得分:0)
尝试使用此代码....
String externalDataPath = Environment.getExternalStorageDirectory() + "/yourFolder";
File f = new File(externalDataPath);
try {
if (!f.exists()) {
f.mkdir();
}
externalDataPath = externalDataPath + "/" + filename;
f = new File(externalDataPath);
if (!f.exists())
f.createNewFile();
externalDataPath = Environment.getExternalStorageDirectory().toString();
} catch (IOException e) {
e.printStackTrace();
}
希望这会有所帮助:)