Storing a file on Internal And External SdCard - android

I am trying to save a file on both internal and external sd card .. basically I want to give user an option to save file on internal or external cards
This is how I am creating file in Internal SD card
File file = new File(Environment.getExternalStorageDirectory()
+ "/Tnt_input/register.html");
but how to create this file in External SD card...?
I can see two storage in DDMS
1) sdCard0
2) extSdCard
by using above code its creating this file in sdCard0

You can use context.getFilesDir() for save file in Internal Storage
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Check saving a file to internal storage for more information.
Note: Your app's internal storage directory is specified by your app's package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable.
Good Example for Save and read file from/to Internal/External storage
how to differentiate between internal and external SD card path in android?

Until Android 4.4 there was no standard way to find all external SD card memories, only one such memory was returned by Environment.getExternalStorageDirectory(). To get to the other memories programmers were parsing some linux configuration files.
Since 4.4 (API 19) there is: Context.getExternalFilesDir which:
Returns absolute paths to application-specific directories on all
external storage devices where the application can place persistent
files it owns. These files are internal to the application, and not
typically visible to the user as media.
so on erlier than 4.4 you should use Environment.getExternalStorageDirectory, and after 4.4 Context.getExternalFilesDir.
There is a good blog post explaining all of this in detail:
http://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html

Finally found a working solution , but its not recomended, to get to external sd card i used hard coded path , like /storage/extSdCard/StorageTest/input but this path depends upon device , the above path works in Samsung Galaxy note series but for xperia Z its /storage/removable/sdcard1. This solution worked for me because my client use a specific device.But like this you cant create a global method which works on every device, so here is the code which worked for me
String galaxy_note = "/storage/extSdCard";
File file = new File(galaxy_note
+"/StorageTest/input");
you can also check if there is a removable sd card installed in device or no by using
Environment.isExternalStorageRemovable();

Related

How to get absolute path of Internal Storage in Android

Internal Storage Path
Consider the above picture. It shows the folders and file in internal storage. My problem is i am not able to get the absolute path of the internal storage. I Have tried using
String path = getFilesDir().getAbsolutePath();
but it is giving me the path of my app storage. My objective is to backup a file from the private storage of my app to the top of internal storage. And i am unable to find a solution on web and neither on stack overflow. Suggest a solution to this problem!
Environment.getExternalStorageDirectory();
Return the primary shared/external storage directory.
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
File dir = Environment.getExternalStorageDirectory();
String path = dir.getAbsolutePath();
It is only possible with root access. You should write you backup to external storage to make it world-readable. Android docs says that if you want to share file with other apps or store this file even after app will be deleted you should save it to external storage. Android docs
Try this,
String path = Environment.getExternalStorageDirectory().getAbsolutePath();

Titanium - Android external storage - create new directory and then write files into it

Can we not simply create new directory programmatically on external SD card (not internal memory of device) in Android and can we not write files on SD card?
Is Titanium so restricted to always write files on internal memory even after using Ti.Filesystem.externalStorageDirectory?
Can someone who has ever been able to create a new directory programmatically on SD card in Android write the answer here or no one ever needs to write something on external SD card?
You can use System class to get storage variables like below
To get the internal SD card you can use
String extStore = System.getenv("EXTERNAL_STORAGE");
File f_exts = new File(extStore);
To get the external SD card you can use
String secStore = System.getenv("SECONDARY_STORAGE");
File f_secs = new File(secStore);
You can choose where to create folder and which one to use.
EDIT
Environment.getExternalStorageDirectory() Details
Return the primary shared/external storage directory.
This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Reference from Environment
Hope it'll help.
try this create folder and file in sdcard
File localFile = new File(Environment.getExternalStorageDirectory(),"/data/create_new_folder_name/");
if (!localFile.exists()) {
localFile.mkdir();
}
try{
File gpxfile = new File(localFile, "yourfilename.xyz");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append("your file text");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
manifest.xml permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use the Storage Access Framework to write on the micro SD card. Google for ACTION_OPEN_DOCUMENT_TREE and ACTION_OPEN_DOCUMENT.
Besides that you can write in a normal way in one app specific directory on the micro SD card. Have a look at the second entry returned by getExternalFilesDirs().

The correct way to create and write to a removable SD card directory on Android 4.4 KitKat and up?

I have spent literally hours now looking for (and trying) many different ways to write some files to my 4.4 Android KitKat's removable SD card after getting countless "eacces permission denied" errors. Seems now that Google has limited access to the filesystem on SD cards you are forced to only be able to write to directories owned by the application (eg: /Android/data/com.mycompany.myapp/files/).
Finally I was able to get something working that creates a directory on the removable SD card that can be written to. However I am curious why in order to gain access to this owned directory on the removable SD card I first had to create a new file object using a path to the external directory?
My implementation:
First I create two globals to house the strings of both the external and removable paths.
MainActivity
public class MainActivity extends ActionBarActivity {
String externalStorageDirectory;//path to owned external storage files
String secondaryStorageDirectory ;//path to owned removable storage files
Then I ask the system what the manufacturer specific directories are called and start concatenating absolute paths for both the externalStorage and removableStorage variables. I also create a new File object initialized with the path to the external app owned directory.
onCreate()
externalStorageDirectory = this.getExternalFilesDir(null).toString();//build absolute path to the app owned external directory
File folder = new File(externalStorageDirectory ); //THIS LINE IS CRUCIAL!!
Log.d("DEBUG", " - External Path" + externalStorageDirectory );// "/storage/emulated/0/Android/data/com.mycompany.myapp/files"
String ownedDirectory = "/Android/data/" + this.getPackageName() + "/files/";
secondaryStorageDirectory = System.getenv("SECONDARY_STORAGE").toString() + ownedDirectory;//build absolute path to the app owned removable directory
Log.d("DEBUG", " - Removable Path"+secondaryStorageDirectory );// "/storage/external/Android/data/com.mycompany.myapp/files/"
Finally I was able to write a file to my application's owned removable SD card directory. And more specifically I was using an AsyncTask to download my files and save them, method #1 of this post.
doInBackground()
output = new FileOutputStream(secondaryStorageDirectory + "myawesomefile.mp4");
Then I was able to navigate to the removable SD card directory via adb shell and I could see my file.
Adb shell output:
//internal storage
shell#QTAQZ3:/storage/emulated/0/Android/data/com.mycompany.myapp/files $ ls
s <
//removable SD card
shell#QTAQZ3:/storage/external/Android/data/com.mycompany.myapp/files $ ls
ls
myawesomefile.mp4
<
And just to reiterate a little:
File folder = new File(externalStorageDirectory); //THIS LINE IS CRUCIAL!!
File folder = new File(secondaryStorageDirectory ); //THIS LINE DOES NOTHING?
So my questions are:
When I create that File object instance, what is happening that makes those directories available?
Why is having to call mkdir() or mkdirs() seem to unnecessary in this case as the dirs magically appear when the file object was created?
And why am I able to see my app's secondary(removable) directory only after I set
the file to the external(non-removable) path?
Admittedly I am relatively new to Android programming, so I'm not even sure if this approach is correct or just a lucky hack? But it seems to work in my app for now.

How can I specify a file path using openFileOutput()?

I've created a program where a user can create an arrayList, and then that list is saved into a text file on the storage device. I used this code from https://developer.android.com/training/basics/data-storage/files.html :
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
I want to find a way to put this onto external storage. I know what you're thinking: Why not just do it like the way they have posted? Well I don't have an external sdcard in my phone, and I use the internal storage, which is still an sd card (When I go to storage settings it shows user application space and internal sd card storage, there is an external sd card storage- I just don't have an sdcard). I know there is an Environment.get... but that is for external. When I use Context.MODE_PRIVATE, it is storing it in the app's folder, but I need the user to be able to access this file, and copy it onto a computer after.
Well I don't have an external sdcard in my phone
That is not external storage. That is removable storage.
When I go to storage settings it shows user application space and internal sd card storage
What an Android device reports to the user, and what the Android SDK reports to you, are different. Internal storage and external storage are both part of the on-board flash. The only difference is that external storage is something that the user (and other apps) can access, while each app's portion of internal storage is inaccessible to most users.
I know there is an Environment.get... but that is for external
getExternalStoragePublicDirectory() on Environment, and getExternalFilesDir() on Context are for external storage. External storage is not removable storage.
When I use Context.MODE_PRIVATE, it is storing it in the app's folder, but I need the user to be able to access this file, and copy it onto a computer after.
Then use getExternalStoragePublicDirectory() on Environment if it fits one of those types of public directories. Otherwise, use getExternalFilesDir() on Context. Both point to locations on external storage, which the user can access (e.g., mount the device as a drive in Windows).

How to access External Micro SD card of the phone?

Does anyone know how can I get SD card of the phone?
I know that someone will tell me its getExternalStorageDirectory() or Environment.getExternalStoragePublicDirectory().
But unfortunately it doesn't always point to the external SD card in all the models. For example I tried in one model of samsung it works fine but another not, LG not. And also according to the documentation also its not always external SD card.
Here it is,
*"don't be confused by the word "external" here.
This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions).
Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer."*
In my application I want user to use SD card only.
How can I overcome with this?
Check out the answer by CommonsWare on the same topic https://stackoverflow.com/a/5695129/582571
He mention that we can not distinguish between mobile's inbuilt external storage and removable external storage.
But by Aleadam answer https://stackoverflow.com/a/6049446/582571 we can only check that is the External Storage is removable or not with isExternalStorageRemovable() function.
I hope you will get idea.
You can below condition to check whether SDCard is available or not
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
//Check for the file
File appFolder = new File(Environment.getExternalStorageDirectory() + File.separator
+ context.getString(R.string.app_name));
boolean exist = appFolder.exists();
}
I was facing the same problem. I didn't know how to access external sd card location. I was developing an app wherein I had to access the external sd card to read and write some stuff. I tried different methods including the pre-defined android libraries. These are the methods I used:-
These were the misses:-
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "test.txt");
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath()+"/Download");
File f = getExternalFilesDir(null);
File file = new File(f,"test.txt");
These all were accessing internal storage "/storage/sdcard0" or "/storage/emulated/0". The reason being in the android device the portion of the internal storage acts as an external storage. So in case you have internal storage of around 16 Gb or more and there is an option to expand the device with sd card, then this is the only way i guess to access the external sd card because even the built-in functions and libraries of the android studio will access internal storage as external storage.
Finally I used this:-
String extFilePath = "/storage/sdcard1/Download";
File myFile = new File(extFilePath, "test.txt");
and it worked. So you see where pre-defined android libraries/functions fail, I was able to do the task with the simple String.
Apart from this if you want to check the path for external storage your device, try this:-
String sdpath,sd1path,usbdiskpath,sd0path;
if(new File("/storage/extSdCard/").exists())
{sdpath="/storage/extSdCard/";
Log.i("Sd Cardext Path", sdpath);}
if(new File("/storage/sdcard1/").exists())
{sd1path="/storage/sdcard1/";
Log.i("Sd Card1 Path",sd1path);}
if(new File("/storage/usbcard1/").exists())
{usbdiskpath="/storage/usbcard1/";
Log.i("USB Path",usbdiskpath);}
if(new File("/storage/sdcard0/").exists())
{sd0path="/storage/sdcard0/";
Log.i("Sd Card0 Path",sd0path);}
Checking these might help you know what path to choose while accessing external sd card. I hope this helps others.
Removable storage path is diff in device to device.
The example of Removable path are:
1. mnt/ext
2. mnt/externalsd
3. mnt/external_sd
My device use mnt/external_sd.
you can check the path of your file from vold.fstab file.
this file is under systems folder.
The path of file is:
"/etc/vold.fstab"
I was facing the same problem with my latest device. Then I found that removable SD card can be accessed at /mnt/ext_sdcard/. and it worked for me. I was able to list all the files stored in removable external sd card at this location.
Following is the code:
new File("/mnt/ext_sdcard/").listFiles();
You can get the path like the following way.....
File sdCardRoot = Environment.getExternalStorageDirectory();
PATH = sdCardRoot.toString();
If the path not exist, then you have to make the path by mkdir().....
private File getTempFile(Context context) {
final File path = new File(Environment.getExternalStorageDirectory(),
context.getPackageName());
if (!path.exists()) {
path.mkdir();
}
return new File(path, "new.png");
}
The above function will return the file...

Categories

Resources