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.
Related
I want to rename my png file. Image current path like this:
/storage/emulated/0/Android/data/sample.png
I want to save this image under app's file directory. I give write external storage permission on runtime.
File toFileDir = new File(getFilesDir() + "images");
if(toFileDir.exists()) {
File file = new File("/storage/emulated/0/Android/data/sample.png");
File toFile = new File(getFilesDir() + "images/sample-1.png");
file.renameTo(toFile);
}
renameTo returns false. But I couldn't understand the reason.
Internal and external memory is two different file systems. Therefore renameTo() fails.
You will have to copy the file and delete the original
Original answer
You can try the following method:
private void moveFile(File src, File targetDirectory) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!src.renameTo(new File(targetDirectory, src.getName()))) {
// If rename fails we must do a true deep copy instead.
Path sourcePath = src.toPath();
Path targetDirPath = targetDirectory.toPath();
try {
Files.move(sourcePath, targetDirPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
throw new IOException("Failed to move " + src + " to " + targetDirectory + " - " + ex.getMessage());
}
}
} else {
if (src.exists()) {
boolean renamed = src.renameTo(targetDirectory);
Log.d("TAG", "renamed: " + renamed);
}
}
}
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.
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
ANSWER:
Needed the call to getExternalFilesDir(p); like so:
String p = thepathblah;
File path=context.getExternalFilesDir(p);
EDIT EDIT:
While I knew the Environment.DIRECTORY_PICTURES was returning just Pictures/ I figured this worked because in android I assumed the file pointer was already pointing to your application space (sorta like in c#). So in this:
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() +
"/" + s.getPackage().getName() +
(mSession.getSessionDate().getMonth()+1) +
mSession.getSessionDate().getDate() +
(mSession.getSessionDate().getYear()+1900);
I thought was getting the full path, in fact I was writing a file out to this with no issues. It turns out though to delete individual files (and load them) I needed a fuller path which ended up being:
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() +
"/" + s.getPackage().getName() +
(mSession.getSessionDate().getMonth()+1) +
mSession.getSessionDate().getDate() +
(mSession.getSessionDate().getYear()+1900);
File dir = new File("/sdcard/Android/data/com.software.oursoftware/files/"+p);
Not sure if I can take it that the above link is valid for all Honeycomb devices or not, specifically the /sdcard/Android/data/packagespace/files/
Is this safe to use this or do I have to do something more dynamic for honeycomb devices???
EDIT: This is my little test function code to just write something to a folder...
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() + "/" + s.getPackage().getName() + (mSession.getSessionDate().getMonth()+1) + mSession.getSessionDate().getDate() + (mSession.getSessionDate().getYear()+1900);
File path = mContext.getExternalFilesDir(p);
File file = new File(path, "DemoPicture.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.ic_contact_picture);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(mContext,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String arg0, Uri arg1) {
Log.i("ExternalStorage", "Scanned " + arg0 + ":");
Log.i("ExternalStorage", "-> uri=" + arg1);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
Then the way I try to delete this folder:
String p = Environment.DIRECTORY_PICTURES + "/" + firstName+lastName +"/" + pName+pDate;
File dir=new File(p);
deleteRecursive(dir);
results in
Pictures/ShaneThomas/Portrait882011/
Which can write a file, tested that, but if I try to say:
void deleteRecursive(File dir)
{
Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
if(temp.isDirectory())
{
Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
deleteRecursive(temp);
}
else
{
Log.d("DeleteRecursive", "Delete File" + temp.getPath());
boolean b = temp.delete();
if(b == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
}
dir.delete();
}
}
The dir.isDirectory is always false!? I got this delete file/directories code off stack overflow but am puzzled as to why its not working?
and I do have this set:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
There are several reasons for File.isDirectory() to return false:
The path points to file (obviously), and not to directory.
The path is invalid (i.e. there is no such file/directory exists).
There is not enough permissions granted to your application to determine whether path points to directory.
In general, if isDirectory() returns true, you've got path that points to directory. But if isDirectory() returns false, then it might be or might not be a directory.
In your particular case, the path most likely does not exist. You need to call dir.mkdirs() to create all directories in the path. But since you need that to only recursively delete them, then there is no point in calling dir.mkdirs() just to remove that directory after that.
I think you want to add
dir.mkdirs() right after File dir=new File(p). mkdirs() is the method responsible for actually creating a directory, not new File().
Ok it's answered, but sometimes the issue fires because of sample reasone:permission :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
if you forgot this permission you will always get false result.
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();
}