i want to write to a file in the sdcard of my phone.i used the below code to do this.
private CSVWriter _writer;
private File _directory;
public String _fileTestResult;
private String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
_writer=null;
_directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
if(!_directory.exists())
_directory.mkdirs();
}
public void exportResult(String testcaseNum,String testcase,String status){
try {
if(_directory.exists()){
//do something
}
but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.
note:i have given the permission in manifest file.
EDIT:
i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?
have you add the correct permission in your manifest ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit : ok, i just read your note for permission.
If it's help you this is my sdcard cache code :
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
String evtDir = "";
if(evt > 0){
evtDir = File.separator + evt;
}
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Android"
+ File.separator
+ "data"
+ File.separator
+ Application.getApplicationPackageName()
+ File.separator + "cache"
+ evtDir);
}else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
Try below code
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
imagefolder = new File(root,
mycontext.getString(R.string.app_name));
imagefolder.mkdirs();
}
} catch (Exception e) {
Log.e("DEBUG", "Could not write file " + e.getMessage());
}
Try with:
if(!_directory.exists())
_directory.mkdir();
Also check this - Creating a directory in /sdcard fails
Related
This is my code
String DATA_PATH="/mnt/sdcard/";
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v("", "ERROR: Creation of directory " + path + " on sdcard failed");
} else {
Log.v("", "Created directory " + path + " on sdcard");
}
}
}
I've tried using Environment.getExternalDirectory() but it still return false. The most confusing thing is it always said "ERROR: Creation of directory mounted on sdcard failed" on the logcat. How can the path changed into mounted? Can someone please give me a solution?
if the mobile is connected to the system then we are not able to create folders so remove it and run the application
Why are you using mkdirs in the first place ? You should just do:
File file = new File(Environment.getExternalStorageDirectory(), "tessdata");
if (!file.exists()) file.mkdir();
Also, make sure you have the WRITE_EXTERNAL_STORAGE permission in the manifest.
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 dir in Sdcard, and i do follow:
I added: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in manifest.
I get root_path by: public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/"; and it returns
/storage/emulated/0/Hello_World (getting when debug).
Next, I run this code:
File file = new File(Constants.ROOT_PATH);
int i = 0;
while (!file.isDirectory() && !file.mkdirs()) {
file.mkdirs();
Log.e("mkdirs", "" + i++);
}
I also tried both mkdirs() and mkdir() but it's showing endless loop in logcat (Log.e("mkdirs", "" + i++);). Sometimes it work, but sometimes not.
Thanks for you helping!
Update: I tried my code for some devices: Nexus4, nexus7, Vega Iron, Genymotion, LG G Pro, then just Vega Iron work as expected. ??!!?!?
Try like this it will create a folder in the sd card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_world");
myDir.mkdirs();
If you want to check that file exists or not use this code
File file = new File (myDir, file_name);
if (file.exists ())
// file exist
else
// file not exist
For reference look at this answer Android saving file to external storage
The error is cause by && in while (!file.isDirectory() && !file.mkdirs()) it should be while (!file.isDirectory() || !file.mkdirs()). You should also check if the media is mounted.
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null)
{
String externalStoragePath = externalStorage.getAbsolutePath();
File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$
if (soundPathDir.isDirectory() || soundPathDir.mkdirs())
{
String soundPath = soundPathDir.getAbsolutePath() + File.separator;
if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$
}
}
}
Cut and paste from one of my project.
Thank all you guys, finally i found out the problem. The problem is in the while() loop, I replace by
if
(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& !file.isDirectory()) {
file.mkdirs(); }
Use Environment.getExternalStorageDirectory().getAbsolutePath() as below...
public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Hello_World/";
And Check that SDCard is mounted before creating directory as below....
File file = new File(Constants.ROOT_PATH);
int i = 0;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if(!file.exists()) {
file.mkdir();
}
}
I want to create a folder in SD card ,and i already add the permission
<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in manifest file.below is my code,but mkdirs return false! Can you help me!
File exportDir = new File(
Environment.getExternalStorageDirectory().toString(), "happydiarybackup");
if (!exportDir.exists()) {
boolean a = exportDir.mkdirs();
Log.d("mkdir ",exportDir.getAbsolutePath() + " make "+ a);
}
Try this. It might help you.
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/happydiarybackup/";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
catch (Exception e) {
Log.e("App", "Exception" + e.getMessage());
}
1.Check your compileSdkVersion
2.Android: mkdirs()/mkdir() on external storage returns false.
Make sure your put the permission tag in.
How do I check if a directory exist on the sdcard in android?
Regular Java file IO:
File f = new File(Environment.getExternalStorageDirectory() + "/somedir");
if(f.isDirectory()) {
....
Might also want to check f.exists(), because if it exists, and isDirectory() returns false, you'll have a problem. There's also isReadable()...
Check here for more methods you might find useful.
File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
// do something here
}
The following code also works for java files:
// Create file upload directory if it doesn't exist
if (!sdcarddir.exists())
sdcarddir.mkdir();
General use this function for checking is a Dir exists:
public boolean dir_exists(String dir_path)
{
boolean ret = false;
File dir = new File(dir_path);
if(dir.exists() && dir.isDirectory())
ret = true;
return ret;
}
Use the Function like:
String dir_path = Environment.getExternalStorageDirectory() + "//mydirectory//";
if (!dir_exists(dir_path)){
File directory = new File(dir_path);
directory.mkdirs();
}
if (dir_exists(dir_path)){
// 'Dir exists'
}else{
// Display Errormessage 'Dir could not creat!!'
}
I've made my mistake about checking file/ directory. Indeed, you just need to call isFile() or isDirectory(). Here is the docs
You don't need to call exists() if you ever call isFile() or isDirectory().
Yup tried a lot, beneath code helps me :)
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "ur directory name");
if (!folder.exists()) {
Log.e("Not Found Dir", "Not Found Dir ");
} else {
Log.e("Found Dir", "Found Dir " );
Toast.makeText(getApplicationContext(),"Directory is already exist" ,Toast.LENGTH_SHORT).show();
}