首先要生成一个文件夹,你需要在AndroidMinifest.xml添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
现在调用以下方法创建一个新文件夹,您要在其中创建文件夹(此名称应存在于 Environment.list 中)和您的文件夹名称。
File outputDirectory = GetPhotoDirectory(Environment.DIRECTORY_PICTURES, "YourFolder");
通过这种方法生成你的文件夹
public static File GetDirectory(String inWhichFolder, String yourFolderName ) {
File outputDirectory = null;
String externalStorageState = Environment.getExternalStorageState();
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(inWhichFolder);
outputDirectory = new File(pictureDirectory, yourFolderName);
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
Log.e(LogHelper.LogTag, "Failed to create directory: " + outputDirectory.getAbsolutePath());
outputDirectory = null;
}
}
}
return outputDirectory;
}
如果要在新创建的文件夹下创建文件,则可以使用以下代码
public static Uri GenerateTimeStampPhotoFileUri(File outputDirectory, String fileName){
Uri photoFileUri = null;
if(outputDirectory!=null) {
File photoFile = new File(outputDirectory, fileName);
photoFileUri = Uri.fromFile(photoFile);
}
return photoFileUri;
}
使用文件目录创建文件夹后调用以创建文件。它将返回您的文件Uri
Uri fileUri = GenerateTimeStampPhotoFileUri(outputDirectory, fileName);