Reputation: 3137
I want to create a file(not created) in a directory(not created) in the SDCARD. How doing it ?
Thank you.
Upvotes: 7
Views: 25691
Reputation: 5053
You can use in Kotlin
val file = File( this.getExternalFilesDir(null)?.getAbsolutePath(),"/your_image_path")
if (!file.exists()) {
file.mkdir()
}
Don't forget to give permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 0
Reputation: 371
Use This:
DocumentFile tempDir = DocumentFile.fromSingleUri(context,targetDirectoryUri);
DocumentFile newDocumentFile = tempDir.createFile(type,name);
"targetDirectoryUri" is uri of the directory you want to put the file into it. This is the only solution! After Api 19 you can not write on SDCard, so you must use DocumentFile instead File. In addition, you must also take SDCard permission. To learn how to do this and get the targetDirectoryUri, please read this.
Upvotes: 2
Reputation: 938
See here why creating files on root of the SD card is a bad idea
Upvotes: -1
Reputation: 33509
Try the following example:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
//create folder
File folder = new File(dir); //folder name
folder.mkdirs();
//create file
File file = new File(dir, "filename.extension");
}
Don't forget to add the permission to your AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 25
Reputation: 1995
The problem is that mkdirs() is called on a File object containing the whole path up to the actual file. It should be called on a File object containing the Path (the directory) and only that. Then you should use another File object to create the actual file.
Upvotes: 3
Reputation: 1107
You should also have to add permission to write to external media. Add following line in the application manifest file, somewhere between <manifest> tags, but not inside <application> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 2