This is what I tried.
private void createFolderInExternalStorage() {
String storagePath = System.getenv("SECONDARY_STORAGE");
Log.e("storagePath->",storagePath);
String path = "not available";
if (storagePath != null) {
Log.e("Path->", "" + storagePath);
File file = new File(storagePath.toString());
Log.e("readable->", "" + file.canRead());
Log.e("writable->", "" + file.canWrite());
Log.e("executable->", "" + file.canExecute());
dir = new File(storagePath + File.separator+etFolder.getText().toString());
if (!dir.exists()) {
dir.mkdirs();
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" created",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" already exists",Toast.LENGTH_SHORT).show();
}
path = dir.getPath();
} else {
Toast.makeText(this,"External Storage not available",Toast.LENGTH_SHORT).show();
}
tv.setText("External SDCARD path->" + path);
}
if Secondary storage is present then System.getenv("SECONDARY_STORAGE") return /storage/sdcard1 in my case but getting following:
03-21 12:02:26.827 14155-14155/com.think.teststorage E/readable->: false
03-21 12:02:26.827 14155-14155/com.think.teststorage E/writable->: false
03-21 12:02:26.828 14155-14155/com.think.teststorage E/executable->: false
Even in some devices getting the above status as true but folder creation fails.
I have added the permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Suggestions are welcome.
You can use this code to create a folder.
File dir = new File("path/of/your/folder");
try{
if(dir.mkdir()) {
System.out.println("Folder created");
} else {
System.out.println("Folder is not created");
}
}catch(Exception e){
e.printStackTrace();
}
Add this permission also :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For further reference : see this link
Let me know if this works for you! :)
Use the following lines:
//Define the path you want
String path = Environment.getExternalStoragePublicDirectory(Environment.YOUR_DIRECTORY) + File.separator + "YourFolderName";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
YOUR_DIRECTORY is the directory where you want to create the folder, for example: DIRECTORY_DOCUMENTS, DIRECTORY_DOWNLOADS, DIRECTORY_PICTURES etc.
In your manifest should to add permission for write:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it help!
It is very simple and straightforward in android
`
File mFolder = new File(Environment.getExternalStorageDirectory(), "Folder_Name");
if (!mFolder.exists()) {
mFolder.mkdirs();
mFolder.setExecutable(true);
mFolder.setReadable(true);
mFolder.setWritable(true);
}
`
Also include required permissions in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Just put these lines of code,
// 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);
and add require permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Does not work on KitKat, external, physical sdcard ??
then use use
Environment.getExternalStorageDirectory().getPath();
Related
I want to create a separate directory for images saved via my app. But I don't know where my code falls short. This is what I am doing to create a new directory in the root directory of external storage:
File root = Environment.getExternalStorageDirectory();
File directory = new File(root,"MYFOLDER");
if(!directory.exists()) {
directory.mkdirs();
}
I have already added the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> permission in my app manifest file. And I have tried this, this and this and others but nothing works.
I use this which works:
private static final String IMAGE_DIRECTORY = "/mydirectory";
File Directory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!Directory.exists()) {
Directory.mkdirs();
}
First give runtime storage permission by adding this lines, Because after android oreo you need to give runtime permission to access storage
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
then you can use this code
File apkStorage = new File(Environment.getExternalStorageDirectory() + "/" + "TestFolder");
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
Add requestLegacyExternalStorage="true" to application tag in manifest file
I have a problem with creating files in Android. I have followed this tutorial, and wrote this method:
public File getStorageDir(String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File file = new File(path, name);
System.out.println(path);
if (!file.mkdirs()) {
System.out.println("Directory not created");
}
return file;
}
Path variable prints /storage/emulated/0/Documents, however if goes off and no such directory is created. I have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
permissions to manifest file. I have tried using file.getParentFile().mkdirs() but got same result. What am I doing wrong?
You use below code to create folder.
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "folderName");
if (!folder.exists()) {
success = folder.mkdirs();
}
So turns out it was being created the whole time, just not visible in file explorer. I have fixed it with answer from this post. Final code looks like this:
public File getStorageDir(Context context, String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath();
File file = new File(path, name);
file.getParentFile().mkdirs();
MediaScannerConnection.scanFile(context, new String[] {path}, null, null);
return file;
}
Thanks everyone for answers, hope this helps someone who faces same problem.
I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
I want to make folders in my sdcard and I have used the code below:
public class Screen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
operateOnFirstUsage();
}
private void operateOnFirstUsage() {
String state = Environment.getExternalStorageState();
Log.d("Media State", state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
File appDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/");
Log.d("appDirectroyExist", appDirectory.exists() + "");
if (!appDirectory.exists())
Log.d("appDir created: ", appDirectory.mkdir() + "");
File dbDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/");
Log.d("dbDirectroyExist", dbDirectory.exists() + "");
if (!dbDirectory.exists())
Log.d("dbDir created: ", dbDirectory.mkdirs() + "");
File themesDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Themes/");
Log.d("themesDirectroyExist", themesDirectory.exists() + "");
if (!themesDirectory.exists())
Log.d("themesDir created: ", themesDirectory.mkdirs() + "");
}
}
}
Also, I have set the sdcard write permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I've run the application several times and every time I get the LogCat output:
01-09 21:38:13.701: D/Media State(15363): mounted
01-09 21:38:13.701: D/appDirectroyExist(15363): false
01-09 21:38:13.701: D/appDir created:(15363): false
01-09 21:38:13.701: D/dbDirectroyExist(15363): false
01-09 21:38:13.701: D/dbDir created:(15363): false
01-09 21:38:13.701: D/themesDirectroyExist(15363): false
01-09 21:38:13.701: D/themesDir created:(15363): false
I have read similar question, but nothing useful to get. What should I do to get the code running? What is my problem?
Edited
Try this:
File mydir = new File(Environment.getExternalStorageDirectory() + "/mydir/");
if(!mydir.exists())
mydir.mkdirs();
else
Log.d("error", "dir. already exists");
And recheck permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is how I created folder MyDir in the Pictures folder od sdcard:
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyDir");
mediaStorageDir.mkdirs();
Try this way:
File file=new File(Environment.getExternalStorageDirectory() + File.separator +"MyApp/");
file.mkdirs();
Try this code:) , its simple.
String fileName = "CallHistory.pdf";
// create a File object for the parent directory
File PDF_Directory = new File("/sdcard/MOBstate/");
// have the object build the directory structure, if needed.
PDF_Directory.mkdirs();
// create a File object for the output file
File outputFile = new File(PDF_Directory, fileName);
// now attach the OutputStream to the file object, instead of a ring representation
FileOutputStream fos = new FileOutputStream(outputFile);
I don't know why the application acted that way, but finally I overcame this problem by removing and resetting the sdcard write permission in the Android manifest file. Thanks all of you for your kind help and apologize for taking your time.
I'm trying to save my file to the following location
FileOutputStream 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.
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?
If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:
// 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.
UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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;
}
Actually I used part of #fiXedd asnwer and it worked for me:
//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
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).
You can read more in the SDK documentation.
Make sure external storage is present:
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);
}
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");
}
}
//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);
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:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
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 dor folder. Like:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and don't forget to add code in manifest
This will make folder in sdcard with Folder name you provide.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
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;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
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);
}
});`