我正在尝试在Android设备的SD卡上的Downloads目录中创建一个文件夹。我在清单中声明了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
。
这是我的代码:
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("file writer", "Directory not writeable");
Toast.makeText(this, "Not writeable.",
Toast.LENGTH_SHORT).show();
}
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "myfolder");
dir.mkdirs();
if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); }
我收到“目录未创建”错误,显然没有文件夹,我打算将其作为一个文件夹。
答案 0 :(得分:0)
你试过这个吗?
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("file writer", "Directory not writeable");
Toast.makeText(this, "Not writeable.",
Toast.LENGTH_SHORT).show();
}else{
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "myfolder");
dir.mkdirs();
if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); } }
答案 1 :(得分:0)
要获得Android 6+的许可,您应该询问用户,试试这个
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
}
}
答案 2 :(得分:0)
试试此代码
File rootPath = new File(Environment.getExternalStorageDirectory(), "Download/myfolder");
if (!rootPath.exists())
rootPath.mkdirs();
希望它有用