Android 如何在SD卡上自动创建目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2130932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create directory automatically on SD card
提问by Kshitij Aggarwal
I'm trying to save my file to the following locationFileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/"
it works.
我正在尝试将我的文件保存到以下位置,FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
但出现异常java.io.FileNotFoundException
但是,当我将路径设置为"/sdcard/"
正常工作时。
Now I'm assuming that I'm not able to create directory automatically this way.
现在我假设我无法以这种方式自动创建目录。
Can someone suggest how to create a directory and sub-directory
using code?
有人可以建议如何创建directory and sub-directory
使用代码吗?
回答by Jeremy Logan
If you create a Fileobject that wraps the top-level directory you can call it's mkdirs()method to build all the needed directories. Something like:
如果您创建一个包装顶级目录的File对象,您可以调用它的mkdirs()方法来构建所有需要的目录。就像是:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note:It might be wise to use Environment.getExternalStorageDirectory()for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
注意:使用Environment.getExternalStorageDirectory()来获取“SD 卡”目录可能是明智的,因为如果手机出现除 SD 卡之外的其他东西(例如内置闪存,等等),这可能会改变苹果手机)。无论哪种方式,您都应该记住,您需要检查以确保它确实在那里,因为 SD 卡可能会被移除。
UPDATE:Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
更新:从 API 级别 4 (1.6) 开始,您还必须请求权限。像这样(在清单中)应该可以工作:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by Daniel
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
有同样的问题,只想添加 AndroidManifest.xml 也需要此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by Vijay Kumar A B
Here is what works for me.
这对我有用。
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in your manifest and the code below
在您的清单和下面的代码中
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
回答by Amt87
Actually I used part of @fiXedd asnwer and it worked for me:
实际上我使用了@fiXedd asnwer 的一部分,它对我有用:
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it Image2.PNG
File file = new File(extStorageDirectory, "Image2.PNG");
Make sure that you are using mkdirs() not mkdir() to create the complete path
确保您使用的是 mkdirs() 而不是 mkdir() 来创建完整路径
回答by Nick Ruiz
With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState()
to check if the media is available. Then you can use getExternalFilesDir()
to navigate to the directory you want (assuming you're using API 8 or greater).
在 API 8 及更高版本中,SD 卡的位置发生了变化。@fiXedd 的回答很好,但为了更安全的代码,您应该使用Environment.getExternalStorageState()
来检查媒体是否可用。然后您可以使用getExternalFilesDir()
导航到您想要的目录(假设您使用的是 API 8 或更高版本)。
You can read more in the SDK documentation.
回答by Parth mehta
Make sure external storage is present: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
确保存在外部存储:http: //developer.android.com/guide/topics/data/data-storage.html#filesExternal
private boolean isExternalStoragePresent() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
.show();
}
return (mExternalStorageAvailable) && (mExternalStorageWriteable);
}
回答by Praveen
Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)
不要忘记确保文件/文件夹名称中没有特殊字符。当我使用变量设置文件夹名称时,我遇到了“:”
not allowed characters in file/folder names
文件/文件夹名称中不允许出现字符
" * / : < > ? \ |
" * / : < > ? \ |
U may find this code helpful in such a case.
在这种情况下,您可能会发现此代码很有帮助。
The below code removes all ":" and replaces them with "-"
下面的代码删除所有“:”并用“-”替换它们
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
回答by Syed Abdul Basit
I faced the same problem. There are two types of permissions in Android:
我遇到了同样的问题。Android 中有两种类型的权限:
- Dangerous(access to contacts, write to external storage...)
- Normal(Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.)
- 危险(访问联系人,写入外部存储......)
- 普通(普通权限Android自动批准,危险权限需要Android用户批准。)
Here is the strategy to get dangerous permissions in Android 6.0
这是在 Android 6.0 中获取危险权限的策略
- Check if you have the permission granted
- If your app is already granted the permission, go ahead and perform normally.
- If your app doesn't have the permission yet, ask for user to approve
- Listen to user approval in
onRequestPermissionsResult
- 检查您是否获得了许可
- 如果您的应用程序已被授予权限,请继续并正常执行。
- 如果您的应用程序还没有权限,请请求用户批准
- 听取用户的认可
onRequestPermissionsResult
Here is my case: I need to write to external storage.
这是我的情况:我需要写入外部存储。
First, I check if I have the permission:
首先,我检查我是否有权限:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check the user's approval:
然后检查用户的批准:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
回答by jayant singh
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
this will create a folder named dor in your sdcard. then to fetch file for eg- filename.json which is manually inserted in dorfolder. Like:
这将在您的 SD 卡中创建一个名为 dor 的文件夹。然后为例如手动插入dor文件夹中的文件名.json获取文件。喜欢:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
< 使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and don't forget to add code in manifest
并且不要忘记在清单中添加代码
回答by Garima Srivastava
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
我遇到了同样的问题,无法在 Galaxy S 上创建目录,但能够在 Nexus 和三星 Droid 上成功创建。我是如何通过添加以下代码行来修复它的:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();