Storing data on SD Card in Android - android

Using the data-storage page in the docs, I've tried to store some data to the SD-Card.
This is my code:
// Path to write files to
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
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();
}
When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory.
Can anyone tell me what I'm doing wrong?
I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".

Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Before reading or writing to SD card, don't forget to check the SD card is mounted or not?
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

Related

write a file to a folder in the android device internal storage

I have a folder, called MyFolder, in the android device internal storage root directory. There is no external sd card mounted. The folder can be checked using says, ES file manager
I want to write a file to that directory.
I try the followings but seem all are not what I want. So how should sd be?
Please help.
File sd = Environment.getExternalStorageDirectory();
// File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) ;
// File sd = new File( Environment.getExternalStorageDirectory().getAbsolutePath());
// File sd = Environment.getRootDirectory() ; // system
// File sd = Environment.getDataDirectory() ;
backupDBPath = "MyFolder/_subfolder/mydata.txt";
File backupDB = new File(sd, backupDBPath);
If your directory located in the internal data directory of your app, you could write the code.
File directory = new File(this.getFilesDir()+File.separator+"MyFolder");
if(!directory.exists())
directory.mkdir();
File newFile = new File(directory, "myText.txt");
if(!newFile.exists()){
try {
newFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fOut = new FileOutputStream(newFile);
OutputStreamWriter outputWriter=new OutputStreamWriter(fOut);
outputWriter.write("Test Document");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
From the official document:
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
The device has removable(SD Card) or non-removable storage(Internal shared storage). Both are called external storage. Suppose you could create the directory in "Internal Shared storage", you could write the code below.
File directory = new File(Enviroment.getExternalStorage+File.separator+"MyFolder");//new File(this.getFilesDir()+File.separator+"MyFolder");
Note: If you have to use getExternalStorage, you should give the storage permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
From an app, you cannot write a file anywhere you'd like on the device's internal storage, it has to be located in the app's internal directory or app cache directory.
When saving a file to internal storage, you can acquire the
appropriate directory as a File by calling one of two methods:
getFilesDir() Returns a File representing an internal directory for
your app.
getCacheDir() Returns a File representing an internal
directory for your app's temporary cache files.
You could write:
String backupDBPath = "/_subfolder/";
String fileName = "mydata.txt";
File file = new File(context.getFilesDir() + backupDBPath, filename);
More infos here:
https://developer.android.com/training/data-storage/files.html

Android: write photo files on SD Card that are viewable in the gallery

I'm trying to found a way (compatible with android kitkat and next) to write photos on the SD Card and make them visible to the gallery app.
If I use Environment.getExternalStoragePublicDirectory , samsung devices return a path in internal memory (/storage/emulated/0/ ... )
If I use Context.getExternalFilesDirs , there are two results : the first one on internal storage, and the second one on SD Card. Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app :'(
I have tried to write directly on /storage/externalSdCard/DCIM/ but of course I can't since I'm running kitkat.
Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app
First, when you are done writing to the file, call flush(), then getFD().sync(), then close(), all on your FileOutputStream.
Then, use MediaScannerConnection and its scanFile() method to get the newly-written file indexed by the MediaStore.
void saveImage() {
File filename;
try {
String path = Environment.getExternalStorageDirectory().toString();
new File(path + "/folder/subfolder").mkdirs();
filename = new File(path + "/folder/subfolder/image.jpg");
FileOutputStream out = new FileOutputStream(filename);
bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName());
Toast.makeText(getApplicationContext(), "File is Saved in " + filename, 1000).show();
} catch (Exception e) {
e.printStackTrace();
}
}

Where should I store a file in Android?

I have an application that creates a configuration file and a log file. I stored these in the external storage, but when I try it in my android emulator it doesn't work because the external storage isn't writable. If this happens, where should I store the files?
This is my code:
private void createConfigurationFile(){
File ssConfigDirectory =
new File(Environment.getExternalStorageDirectory()+"/MyApp/config/");
File file = new File(ssConfigDirectory, mUsername+".cfg");
if(!file.exists()){
try{
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)){
ssConfigDirectory = new File("PATH_WHERE_I_SHOULD_STORE_IT");
}
File ssLogDirectory = new File(ssConfigDirectory+"/SweetSyncal/log/");
ssLogDirectory.mkdirs();
ssConfigDirectory.mkdirs();
File outputFile = new File(ssConfigDirectory, mUsername+".cfg");
FileOutputStream fOut = new FileOutputStream(outputFile);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
writeFile(osw);
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
If the file isn't too big you can save it in the device's Internal Storage.
To access the Internal Storage you can use the following method:
FileOutputStream openFileOutput (String name, int mode)
(You need an instance of Context to use it)
Example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
As to why the code you provided is not working then there are two possibilities:
You forgot to add the required permission (WRITE_EXTERNAL_STORAGE).
You'r emulator doesn't have an SD card enabled. Assuming you are using Eclipse you can enabled it in the AVD Manager. Just edit your AVD instance and type in the size of the SD card in the appropriate field. You should also add a hardware feature called SD Card Support and set it to TRUE.
There is a great article in the official Developer Guide which will tell you everything you need to know about storage in Android.
You can read it HERE

android error trying to write to external SD

I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.

Android SD card path inaccessible

I have a knock off android device HT-PAD1051
But, really having trouble accessing the root directory in the built in sd card. card is partitioned and what is called "mnt/extsd" is accessible. Any ideas on how to get at root?
The device has been rooted.
Thanks
Joe
For any android device, If you want to get external storage always use.
Environment.getExternalStorageDirectory();
instead of giving hard coded path.
public void writeFile(String text){
try{
Writer output = null;
File dir = new File(Environment.getExternalStorageDirectory() + "/RequiredDirectory");
dir.mkdirs();
File file = new File(dir,<filename>);
output = new BufferedWriter(new FileWriter(file,true));
output.write(text);
output.close();
System.out.println("Your file has been written");
}catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources