My app allows user to take a picture and I want that picture to be stored in the app's external files directory (getExternalFilesDir(null)). It all works except for the call to renameTo(), this call returns false and I don't know why.
The src file is:
/storage/extSdCard/DCIM/Camera/20140424_154458.jpg
Dest file is:
/storage/emulated/0/Android/data/com.myapp.myapp/files/20140424_154458.jpg
I also have specified the WRITE_EXTERNAL_STORAGE permission.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.action_take_picture)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE);
return true;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK)
{
File dest = new File(
getExternalFilesDir(null),
new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.getDefault()).format(new Date()) + ".jpg");
File src = new File(convertMediaUriToPath(data.getData()));
if (src.renameTo(dest)) // Always returns false
{
mAdapter.add(dest);
mAdapter.notifyDataSetChanged();
}
}
}
private String convertMediaUriToPath(Uri uri)
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
I have ran into this problem previously - unfortunately, you are not allowed to use renameTo to move files and/or directories between different mount points (for example, internal and external storage). Consider using a different way of moving files, such as the one outlined here:
http://www.mkyong.com/java/how-to-copy-directory-in-java/
public static void copyFolder(File src, File dest) throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
The problem is with the method renameTo, the renameTo doesn't create subdirectories,
Reason being The current File API isn't very well implemented in Java. There is a lot of functionality that would be desirable in a File API that isn't currently present such as move, copy and retrieving file metadata.
I don't think anyone will be able to give you an answer as to why the API is written as is. Probably a poor first draft that went live and couldn't be changed due to backwards compatibility issues.
These issue have been addressed in the Java 7. A entirely new API has been created to deal with files java.nio.file.Files.
To Solve this issue, try to get directory path of destination file
e.g /storage/emulated/0/Android/data/com.myapp.myapp/files/20140424_154458.jpg
Destination Directory is
/storage/emulated/0/Android/data/com.myapp.myapp/files/
Use mkdirs() , it will create all sub directories for you
If you want to add a file or folder or move application into your SD Card just do the following:
steps:
1) Open your Android application's source code file with a text or programming editor. 2) Browse to the location in the source code where you wish to call the function that writes a file to the device's external storage. 3) Insert this single line of code to check for the SD card:
File sdCard = Environment.getExternalStorageDirectory();
4) Insert these lines of code to set the directory and file name:
File dir = new File (sdcard.getAbsolutePath() + "/folder1/folder2");
dir.mkdirs();
File file = new File(dir, "example_file");
// The mkdirs function will create the directory folder for you, use it only you want to create a new one.
5) Replace "/folder1/folder2" in the above code with the actual path where you intend to save the file. This should be a location in which you normally save your application files. Also, change the "example_file" value to the actual file name you wish to use.
6) Insert the following line of code to output the file to the SD card:
FileOutputStream f = new FileOutputStream(file);
Finally step 7:
Save the file, then compile it and test the application using the Android emulator software or the device.
This will work!!! ;-)
Related
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 have got a problem with backup database in my app. I am working on Android 2.2.3 and this has sd card installed. Making copy of the database works fine. The problem occures when I'am testing my app on the phone with internal memory enought big like sd cards (Nexus 32gb). In this scenario my method doesn't work extracting file to sd card because it doesn't (sd card) exist. How to make copy of database to internal independed location? I've tried:
File outPut = new File(Environment.getRootDirectory().toString() + "/myfolder/");
but got permission denied and can not create folder with data. Can anyone show correct way?
EDITED:
I don't get it. I'd like to make new folder with dataBackup. I've defined correct location for that but it says that can not find file. SDCard is present. Why it can not create that folder - "/storeUGif/databaseName.db".?
Here is absolute path for destination folder:
public static final String OUTPUT_BACKUP_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/storeUGif/" + SqliteHelper.DATABASE_NAME;
if(isSdPresent())
{
//File outPut = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/StoreUGif/"+SqliteHelper.DATABASE_NAME);
File outPut = new File(Tools.OUTPUT_BACKUP_DATABASE);
File storeUGif = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString());
storeUGif.mkdir();
File currentDB = getApplicationContext().getDatabasePath(SqliteHelper.DATABASE_NAME);
FileInputStream is = new FileInputStream(currentDB);
OutputStream os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
else
{
Toast.makeText(this, "SDCard is unvailable", Toast.LENGTH_SHORT).show();
}
Use Environment.getExternalStorageDirectory() to get a valid path.
Despite its name, it will return the default storage, either the external or (if missiing) the internal one.
For reference: http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()
It looks like I can not play videos stored in my internal application directory.
I have videos stored in /data/data/my.package.org/files/
And I'm trying to play a file from there using
String fpath = "/data/data/my.package.org/files/video.mpg"
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(fpath), "video/*");
But both Android default video player and some external videoplayer (MX player) say 'this video can not be played".
Whereas when I'm saving videos to SD card they are played fine.
Why is that?
Put your video in assets folder and use this code to play video with MediaPlayer
InputStream is = getResources().getAssets().open("video.mpg");
OR
Put your video in assets folder and...
String fpath = "/data/data/my.package.org/assets/video.mpg"
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(fpath), "video/*");
put your video in the res\raw folder. Then copy it out to the external directories where apps like video player can read them. Only your app can read /data/data/blah....
if its in res\raw, then
typeName = sourceSink.Types.video.toString();
for (sourceSink.VideoFiles video: sourceSink.VideoFiles.values() ){
resourceName = video.toString();
fileName = resourceName + ".mp4";
resource = getResources().getIdentifier(resourceName, "raw", "com.invodo.allshareplay");
createExternalStoragePublicFile(typeName,fileName,resource);
}
and then you can use this to copy it:
void createExternalStoragePublicFile(String fType, String fname, int res ) {
// Create a path where we will place our picture in the user's
// public pictures directory. Note that you should be careful about
// what you place here, since the user often manages these files. For
// pictures and other media owned by the application, consider
// Context.getExternalMediaDir().
File path = null;
if (((fType.equals(sourceSink.Types.photo.toString())) || (fType.equals(sourceSink.Types.file.toString())) ) ){
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
}
if (fType.equals(sourceSink.Types.music.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
}
if (fType.equals(sourceSink.Types.video.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
}
File file = new File(path, "/" + fname);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// 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(res);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
scanMedia(file);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
then it's easy - just do the second half of the answer I provided and write them out. /data/data/ folder is never going to be viewed by anything other than your app.
ey up. ive built a simple music app that reads wav files from the sdcard and plays them.
how do i access the default media directory?
this is how i get the sdcard
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
File sd = new File(Environment.getExternalStorageDirectory ()); //this needs to be a folder the user can access, like media
as usual the docs dont give an actual example of usage but it says this - If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC...
how do i use it?
thank you
edit:
this makes it crash if i try to fill a spinner array with file path Strings.
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File sd = new File(path, "/myFolder");
File[] sdDirList = sd.listFiles(new WavFilter());
if (sdDirList != null)
{
//sort the spinner
amountofiles = sdDirList.length;
array_spinner=new String[amountofiles];
......
final Spinner s = (Spinner) findViewById(R.id.spinner1); //crashes here
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,
android.R.layout.select_dialog_item, array_spinner);
EDIT2:
ok so ive done this test that is supposed to write a txt file to the music directory.
i run the app, no txt file is written anywhere on the device i can find.
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
another edit: i will get this working!!
so if i use this line it creates a folder on the sdcard called 'Musictest'. dont understand??
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "test").getAbsolutePath();
////////////////////////////////////////////////////////////////////
Final Edit:
right so this will look for a folder called test in the devices music directory.
if it doesnt exist, it will be created.
(some fixing to be done here, error if empty) it then lists the files in the directory and adds them to an array.
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/test").getAbsolutePath();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
// Make sure the path exists
boolean exists = (new File(path)).exists();
//if not create it
if (!exists){ new File(path).mkdirs(); }
File sd = new File(path);
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
//add the files to the spinner array
array_spinnerLoad=new String[sdDirList.length];
files = new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++){
array_spinnerLoad[i] = sdDirList[i].getName();
files[i] = sdDirList[i].getAbsolutePath();
}
}
}
}
as mentioned in the docs, getExternalFilesDir() return File. And File object can represent either file or directory.
Therefore:
File musicDirectory = new File( getExternalFilesDir(Environment.DIRECTORY_MUSIC));
Will give you the object to play with.
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);
}
});`