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
Related
I'm trying to generate a folder with my android application in my phone storage (not on the sdcard) but my mkdirs() is not working.
I have set the android.permission.WRITE_EXTERNAL_STORAGE in my manifest and use this basic code :
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "/MyDirName");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
}
}
but it doesn't work ... The mkdirs is always at false and the folder is not created.
I have tried everything and looked at all the topics about it but nothing is working and I don't know why.
if you target and compile sdk is higher then lolipop then please refer this link
or
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
If you you the emulator and the Device File Explorer of Android Studio, be sure that you right-click over a folder of the emulator and then click on 'synchronize' to update the files displayed. The Device File Explorer doesn't update by itself in real time.
when writing code for android API 29 and above use the following permission in your application manifest (AndroidManifest.xml)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Then in your java file add the following lines of code
`ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
PackageManager.PERMISSION_GRANTED);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
file = new File(Environment.getExternalStorageDirectory().getPath(), "MyDirName/");
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
`
I'm trying to create a directory and save a file into the directory, my program returns that the directory was created, but I can not find the directory using either the USB port to explore from a PC, or using ES file Explorer. The program also returns true (that the directory was created) every time I run the program, if it did create it, it should return true only the first time. Additionally when I try to create a file within the directory it returns that the file does not exist. In the manifest I am setting user permissions for write to both external and internal storage.
Please advise what I'm doing wrong, why does my program not actually create a folder (or file) (note that the tager folder path is storage/emulated/0/Documents/Saved_Receipts), which I assume will end up being /My Documents/Saved_Receipts)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
boolean success = false;
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
if (!myDir.exists()) {
success = myDir.mkdir();
textIncoming.append("creating folder");
}
if (success) {
textIncoming.append("created folder");
} else {
textIncoming.append("folder existed");
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt_.xml";
File file = new File (myDir, fname);
if (file.exists ()) {
textIncoming.append("file exists");
}
else{
textIncoming.append("file does not exist");
}
You are probably using SDK (API) 23 or higher. If that's the case, declaring permissions in the manifest is no longer enough.
You should be able to fix that issue by adding the following block in your code:
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
See:
Storage permission error in Marshmallow
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();
I am trying to save a file in my External SDcard but the file is getting stored in internal storage. How to store the file in the SDcard inserted
mr = new MediaRecorder();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
Log.e("aa","sss");
cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(), "Recorder");
} else {
cameraFolder= getDir("Recorder",MODE_PRIVATE);
}
if(!cameraFolder.exists()) {
cameraFolder.mkdir();
}
fname = cameraFolder + "/myrec1.MPEG_4";
There is already a similar question here, you can also find more detailed information on the android docs
As suggested in a comment below I'll improve this answer.
In order to save a file to a specific position in your SD card you need to create a File object which points to that position:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/your/file/directory");
dir.mkdirs();
File file = new File(dir, "filename");
and then use a FileOutputStream to write the content.
Remember that you need to add the required permission in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
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);
}