Writing to the SD card - android

I want to write to the physical SD card in my Android phone.
This is my code:
File sdCard = Environment.getExternalStorageDirectory();
String state = Environment.getExternalStorageState(); //shows mounted
boolean removable = Environment.isExternalStorageRemovable(); //shows false
I know that the external in getExternalStorageDirectory() not necessarily means the SD card. When I write a file to sdCard object it ends up in the internal (means build in) storage and not on the sdCard.
On my mobile I have multiple apps which write data to the sdCard, e.g. file explorer. How do they do it? I want to force to write to sdCard regardless what the manufacturer thinks is internal/external.

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
...

Caution: Files on external storage are not always accessible, because users can mount the external storage to a computer for use as a storage device. So if you need to store files that are critical to your app's functionality, you should instead store them on internal storage.
Request external storage permissions
To write to the public external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Note: If your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.
If your app only needs to read the external storage (but not write to it), then you need to declare the READ_EXTERNAL_STORAGE permission:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
https://developer.android.com/training/data-storage/files.html
Now, let's say that for example you want to record a text file in your SD ...
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();

Related

How to make a folder on external SDCARD (Which is inserted from out side the device)?

I need to create a folder on my external storage (inserted SD card). I tried in several ways, but it just create a folder on device storage. I have seen to create on some android app. Please help me by providing a solution. Thanks in advance.
File directory = new File(Environment.getExternalStorageDirectory() + "/boyan/");
if (!directory.exists()) {
directory.mkdirs();
}
Permissions are:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Do it like this
File file = new File(Environment.getExternalStorageDirectory(), "Folder_name");
if (!file.exists()) {
file.mkdirs();
}
I got the solution.
Here it is.
Environment.getExternalStorageDirectory()
Above code return "/storage/sdcard0", But if you want to make a folder on external SD Card you need "/storage/sdcard1". so try to do something like this
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().replace("0", "1") + "/boyan/");

Nothing Happening when trying to write to file on SD card android

I am using the following code to write to an SD card:
File dir =new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
if(!dir.exists())
{
dir.mkdirs();
}
String filename= "MyDoople.txt";
try
{
File f = new File(dir+File.separator+filename);
FileOutputStream fOut = new FileOutputStream(f);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append("Mytest");
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Text Updated",
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
However when I run my app, and then go check in the SD card, there is nothing there. Why am I not seeing the file that I created? I am using android jellybean 4.1 and have added the write permissions in the manifest file.
From your code, you're writing to the folder "MyFolder" under primary external storage.
What is the device you are using? Does it have interal storage in additional to sd card? If yes, then your file is written to the internal storage, but not the sd card.
Edit:
To access SD Card, you simply replace android.os.Environment.getExternalStorageDirectory() with the sd card path.
It is not an easy task to find the path of SD card.
One method is to use ContextCompat.getExternalFilesDirs(context, null), the first element of the returned value would be the same android.os.Environment.getExternalStorageDirectory(), the second element would be somewhere of the sdcard.
However, could be depending on your android version, the directory returned could be a sub-directory on the sd card, i.e. your application specific directory instead of the root of SD card. You have to check and manually change it if you want to find the root directory.
http://developer.android.com/reference/android/support/v4/content/ContextCompat.html#getExternalFilesDirs%28android.content.Context,%20java.lang.String%29

Android, issue with finding saved file on storage

I am downloading a file(PDF) from server using DownloadManager and request is
request.setDestinationInExternalFilesDir(this,Environment.getDataDirectory().getPath(), filename);
The File gets save in my internal storage under
"MyFiles->All files/DeviceStorage/Android/data/myPackage/files/data/"
For opening the saved file i use the following code
File sdCardRoot = new File(Environment.getDataDirectory().getPath());
if(sdCardRoot.exists()){
for (File f : sdCardRoot.listFiles()) {
if (f.isFile())
name1 = f.getName();
String path = f.getPath();
Log.e("UriFile", ""+Uri.parse(path));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(path), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
But it shows document cannot be opened, But i can see the file in the location and can open it directly not from my app.
I have a SD card inserted and there is a similar folder structure created in sdcard as well .
I guess while opening the file it searches the folder on SDCARD not my internal storage, how to solve this.
Have you added permissions in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
As your file is stored in app internal storage i.e /data/data/packagename/ use getFilesDir() to get the path of directory holding application files & use listFiles() to get all files inside returned path directory.
getFilesDir() - Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored. No permissions are required to read or write to the returned path, since this path is internal storage.
OR you can use getExternalFilesDir(String type) to get the path of directory where you app files are saved & iterate through files using listFiles().
getExternalFilesDir(String type) - Returns the absolute path to the directory on the primary external filesystem (that is somewhere on Environment.getExternalStorageDirectory()) where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
Usage Example:
public void listFilesInAppInternalStorage(){
//using getFilesDir()
File filesDir = getFilesDir();
File filesList[] = filesDir.listFiles();
for(File file: filesList){
Log.i(TAG, "FileName:" + file.getName());
}
//using getExternalFilesDir()
File extFilesDir = getExternalFilesDir(null);
File listOfFiles[] = extFilesDir.listFiles();
for (int i=0; i < listOfFiles.length; i++)
{
Log.v(TAG, "FileName:" + listOfFiles[i].getName());
Log.d(TAG, "FilePath:" + listOfFiles[i].getAbsolutePath());
}
}

Android creating text file

I want to create/write new files on the device.
I am able to create file on sd card of the android device.
But in case if device is not having sd card then where should i create file which can be accessible from the ddms.
I tried to create it in /data/data/com.abc.app/files/ directory, But i don't have permissions to access this directory from the ddms to save the file on pc.
Which is the best location create new file on the device which can be access from ddms and application.
Try use cache dir local and external.
Here is a part of my code
File dir = context.getExternalCacheDir() != null ?
context.getExternalCacheDir() : context.getCacheDir();
File file = new File(dir, ".cachefile");//hidden
if (file.exists())
file.delete();
FileOutputStream out = new FileOutputStream(file);
//..
out.flush();
out.close();
Don't forget to have permissions read/write;
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have the permission to write/read in/from that folder through your applicatin. You have to use the pair openFileInput/openFileOutput
here the doc per openFileInput/openFileOutput

save image to sdcard android Directory problem

Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:
FileOutputStream os;
dirName = "/mydirectory/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + dirName);
dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
File file = new File(dir, dirName+fileName);
os = new FileOutputStream(file);
}else{
os = context.openFileOutput(fileName, MODE_PRIVATE);
}
resizedBitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
}
ErrorLog:
java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)
Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?
Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.
Edit - to create directories:
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();
Then you can save a file to root + "/mvc/mvc/foo.png".
Have you requested permission to write onto SD card? Add the following string to you app manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should check if you have added the required permission android.permission-group.STORAGE to your app. Without that permission you won't be able to access anything on the SD-Card.
BTW: On the Android system I know the SD-card is mounted on /sdcard not /mnt/sdcard
I found this book to be very helpful: "Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets". I noticed a part that allows saving images and stuff to the SD card.

Categories

Resources