android - 如何在SD卡上自动创建目录

我正在尝试将文件保存到以下位置

directory and sub-directory但是我得到了例外java.io.FileNotFoundException

但是,当我把路径作为"/sdcard/"时,它的工作原理。

现在我假设我无法以这种方式自动创建目录。

有人可以建议如何使用代码创建directory and sub-directory吗?

15个解决方案

433 votes

如果您创建一个包装顶级目录的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);

注意:使用Environment.getExternalStorageDirectory()来获取“SD卡”目录可能是明智之举,因为如果手机出现了除SD卡以外的其他东西(例如内置闪存,则可能会更改) 苹果手机)。 无论哪种方式,您都应该记住,您需要检查以确保它实际存在,因为可能会移除SD卡。

更新:自API级别4(1.6)起,您还必须请求许可。 这样的事情(在清单中)应该有效:

Jeremy Logan answered 2019-04-03T13:02:01Z

57 votes

有同样的问题,只想添加AndroidManifest.xml也需要此权限:

Daniel answered 2019-04-03T13:02:34Z

39 votes

这对我有用。

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

在你的清单和下面的代码中

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;
}

Vijay Kumar A B answered 2019-04-03T13:03:14Z

22 votes

实际上我使用了部分@fiXedd的答案,它对我有用:

//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");

确保使用mkdirs()而不是mkdir()来创建完整路径

Amt87 answered 2019-04-03T13:03:55Z

12 votes

使用API 8及更高版本,SD卡的位置已更改。 @ fiXedd的答案很好,但是为了更安全的代码,你应该使用Environment.getExternalStorageState()来检查媒体是否可用。 然后,您可以使用getExternalFilesDir()导航到所需的目录(假设您使用的是API 8或更高版本)。

您可以在SDK文档中阅读更多内容。

Nick Ruiz answered 2019-04-03T13:04:34Z

8 votes

确保存在外部存储:[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);
}

Parth mehta answered 2019-04-03T13:05:02Z

6 votes

我遇到了同样的问题。 Android中有两种类型的权限:

危险(访问联系人,写入外部存储...)

正常(Android会自动批准普通权限,而Android用户需要批准危险权限。)

以下是在Android 6.0中获取危险权限的策略

检查您是否已获得许可

如果您的应用已获得许可,请继续正常运行。

如果您的应用尚未获得许可,请要求用户批准

在onRequestPermissionsResult中收听用户批准

这是我的情况:我需要写入外部存储。

首先,我检查一下我是否有权限:

...
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);
}

然后检查用户的批准:

@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();
}
}
}
}

Syed Abdul Basit answered 2019-04-03T13:06:51Z

5 votes

我遇到了同样的问题,无法在Galaxy S上创建目录,但能够在Nexus和Samsung Droid上成功创建目录。 我如何修复它是通过添加以下代码行:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();

Garima Srivastava answered 2019-04-03T13:07:18Z

5 votes

不要忘记确保文件/文件夹名称中没有特殊字符。 当我使用变量设置文件夹名称时,用“:”发生在我身上

不允许文件/文件夹名称中的字符

“* /:<>?\ |

你可能会发现这个代码在这种情况下很有帮助。

下面的代码删除所有“:”并用“ - ”替换它们

//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");
}
}

Praveen answered 2019-04-03T13:08:18Z

5 votes

File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();

这将在你的SD卡中创建一个名为dor的文件夹。然后获取eg- filename.json的文件,手动插入dor文件夹。 喜欢:

File file1 = new File(sdcard,"/dor/fitness.json");

.......

.....

&LT; uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/&gt;

并且不要忘记在清单中添加代码

jayant singh answered 2019-04-03T13:09:03Z

4 votes

//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);

vikseln answered 2019-04-03T13:09:22Z

3 votes

刚刚完成Vijay的帖子......

表现

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

功能

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;
}

用法

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
你可以检查错误
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}

Ismael Di Vita answered 2019-04-03T13:10:05Z

3 votes

这将使sdcard中的文件夹具有您提供的文件夹名称。

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}

Shweta Chauhan answered 2019-04-03T13:10:34Z

1 votes

您可以使用/ sdcard /而不是Environment.getExternalStorageDirectory()

private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/";
File dbdir = new File(DB_PATH);
dbdir.mkdirs();
Peter Drinnan answered 2019-04-03T13:11:05Z
1 votes
ivmage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`
Vishnu Namboodiri answered 2019-04-03T13:11:27Z