How can i get extSdcard path in android?
There are 2 storage, first external storage in which all the phones have it but there is second storage which is called removable storage (micro sdcard).
I want to get the path to the micro sdcard in android, how is that possible?
Starting from KitKat, you have access to a method to get that directory :
Context.getExternalFilesDirs()
Note that it may return null if the SD card is not mounted or moved during the access. Also, you might need to add these permissions to your manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Apparently some users had trouble with this method, not returning the SD card path. I found some useful informations on how it can works and how it can not depending on the device on this post.
Check this https://developer.android.com/guide/topics/data/data-storage.html#filesExternal for complete reference as you need to define permission to read and write to the external SD also there is code in the above link which checks if SD card is available before performing any action
The following works for me!
File[] Dirs = ContextCompat.getExternalFilesDirs(this.getApplicationContext(), null);
File path = (Dirs[1]);
String pathSD = Dirs[1].toString();
int firstOpen = pathSD.indexOf("/");
int secondOpen = pathSD.indexOf("/", firstOpen + 1);
int thirdOpen = pathSD.indexOf("/", secondOpen + 1);
String filename = pathSD.substring(firstOpen, thirdOpen + 1);
path = new File(filename);
As of API level 24, you can use the StorageManager class:
https://developer.android.com/reference/android/os/storage/StorageManager#getStorageVolumes()
Related
I am trying to find out the Ad Junk present (Files which are Downloaded by the AD SDK of other apps).
This is what I have been able to find out till now -
I am loading the list of all the files in the devices and them checking them and grouping them like this
if (file.getPath().toLowerCase().endsWith(".temp") )
{
//Temp Files found
}
else if (file.getName().endsWith(".apk") && file.canWrite())
{
//Apk Files found
}
There are many other cleaner which find out the junk files present in the Device. Even I am trying to achieve the same. Can any one help me on how to identify whether the file is an AD Junk file or not?
You can Delete Junk File by
File[] files = getBaseContext().getCacheDir().listFiles();
for (File file : files) {
file.delete();
}
And Put this permissions in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You could check the codebase of some Open Source Cleaner, like: https://github.com/mzlogin/CleanExpert
or
https://github.com/DroidsOnRoids/android-device-cleaner
and see how they do it.
I'm trying to copy a file that is located in the External storage directory into a directory that is in my SD Card. However, when I check to see if the file has successfully been copied, the file is not even created in the SD Card.
Am I missing something? Here is the code I have:
String sourcePath = Environment.getExternalStorageDirectory().getPath() + newFileName;
File source = new File(Environment.getExternalStorageDirectory().getPath(), newFileName);
String destinationPath = "/storage/external_SD";
File destination = new File(destinationPath, newFileName);
try {
if(!destination.exists()){
destination.mkdir();
}
FileUtils.copyFile(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
The copyFile method is from an Apache library. Here is the link for it: https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
However, when I check to see if the file has successfully been copied, the file is not even created in the sd Card.
You do not have arbitrary filesystem-level access to removable storage on Android 4.4+.
Is there a work around for this?
That depends on what your objective is.
If you insist that you must be able to write to that specific path on arbitrary user devices... then, no, there is no supported workaround. After all, there is no /storage/external_SD on the vast majority of Android devices. Where and how device manufacturers choose to mount removable media is up to them and is an implementation detail that will vary.
If you relax that restriction, but insist that you must be able to write a file to the root directory of removable storage on arbitrary user devices... then, no, there is no supported workaround today. The N Developer Preview has a "Scoped Directory Access" feature that should allow this, but it will be several years before you can assume that an arbitrary user device will be running that version of Android or higher. Also, you do not get actual filesystem access, but rather a Uri (see the Storage Access Framework option, below).
Now, if you are more flexible about the precise location, you have other options:
You can use getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs(), all methods on Context. Note the plural form. If those return 2+ entries, the second and subsequent ones are locations on removable storage that you can read from and write to, no permissions required. However, you do not get to choose the exact path. And if the device has 2+ removable storage volumes, I'm not quite certain how you would help the user tell them apart.
You can use the Storage Access Framework and let the user choose where to put the file. The user is welcome to choose removable storage... or not. You get a Uri back, which you can use with ContentResolver and openOutputStream() to write your content. You can also take persistable Uri permissions so you can work with that file again in the future, assuming the user doesn't move or delete it behind your back.
If you want to copy to external storage then you need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The destinationPath you mentioned may not be accessible as it may belong to the private system folders or some other application folders. You can however use public folders like Pictures,Music, Videos,Downloads,etc. or create sub folders inside them -
String sourcePath = Environment.getExternalStorageDirectory().getPath() + newFileName;
File source = new File(Environment.getExternalStorageDirectory().getPath(), newFileName);
File destinationPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS, "/external_SD");
try {
if(!destinationPath.exists()){
destinationPath.mkdir();
}
File destination = new File(destinationPath, newFileName);
FileUtils.copyFile(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
I am trying to access WhatsApp database folder exists in Environment.getExternalStorageDirectory().getAbsolutePath() + /WhatsApp/Databases location in un-rooted device.
My aim is to collect these files and decrypt them and show each messages to Web portal. Here is the code to collect these files:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + location;
f = new File(path);
final File file[]=f.listFiles();
final int size = file.length;
Whenever i am running on rooted device, It is working but on some unrooted devices it is throwing nullpointer because it is not able to get the list of all database files.
My question is: Is it possible to ready WhatsApp Database files when device is not root?
or is there any way to do it?
I am not sure the root effects. Have you get the PERMISSION for your app ? if not, you can try to put uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE on your manifest and then test it.
you are able to read database file try below code its worked if device is not rooted.
i have tried these in Samsung Grand 2, HTC
String path = Environment.getExternalStorageDirectory()
+ "/WhatsApp/Databases";
File file = new File(path);
if (file.exists()) {
File[] filenames = file.listFiles();
for (File tmpf : filenames) {
// Do something with the files
if (tmpf.isFile()) {
Log.e("tmpf-------->", "not add---->" + tmpf.getPath());
}
}
} else {
Log.e("folder not found", "folder not found");
}
don't forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
No, You can't get SQLite databse file from an Android device if it's not rooted, since you have no permission to access data folder.
But yes you can get database if you run app on emulator.
I tried a simple file write program in Android.
try
{
//File f1=new File("/sdcard/Prag.txt");
File f1=new File("J:\\Prag.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1,true));
out.write("Pragadheesh" + "\n");
out.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
But the exception is getting hit. How can I fix this?
[edit]:
I tried File f1=new File(Environment.getExternalStorageDirectory() + "//Prag.txt");
and f1 value = /mnt/sdcard/Prag.txt
But still the exception gets hit. I have changed the permission too in manifest file
[solution]
As per Krishnabhadra's reply, I had to Make sure your SDCard is not mounted on a PC
Android is based on linux so windows style paths like "J:\\prag.txt" won't work. In linux paths are like this: "/folder1/folder2/file.txt"
Also don't use hardcoded paths, because different phones might have different path for the SD card. Therefore you you should use Environment.getExternalStorageDirectory() that gives the path to the SD card programmatically.
So use:
File f1=new File(Environment.getExternalStorageDirectory() + "Prag.txt");
Also add necessary permission by:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Inside your manifest, somewhere outside application tag.
All the above answers are useful..But remember one more thing..Make sure your SDCard is not mounted on a PC. Only one device can access SDCard at one time. ie either the computer or the phone can access the SD card, but not both at the same time..If it is mounted on PC then your code won't work..See this thread
Replace:
File f1=new File("J:\\Prag.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1,true));
with:
BufferedWriter out = new BufferedWriter(new FileWriter(Environment.getExternalStorageDirectory(),"prag.txt"))
Have you set the required permission in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
what is this path "J:\Prag.txt" ; Android doesn't recognize any drive path like system.
Use sdcard path for it.
File f1=new File(Environment.getExternalStorageDirectory()+"/Prag.txt");
Also mention permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Im trying to build a directory called "images" on the SD card on android. This is my code but its not working? Can anyone give me some advice?
File picDirectory = new File("mnt/sdcard/images");
picDirectory.mkdirs();
Update: Since Android 10,11 Storage updates, Google has restricted Storage access through standard programming language file operations.
For applications targeting only Android 10 (API 29) and above, you need to declare "requestLegacyExternalStorage="true" " in your android manifest file to use programming language based file operations.
<application
android:requestLegacyExternalStorage="true"
....>
==========
You want to be sure you are correctly finding the address of your SDCard, you can't be sure its always at any particular address. You will want to do the following!
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"images");
directory.mkdirs();
Let me know if this works for you!
You will also need the following line in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I use this to know the result:
File yourAppDir = new File(Environment.getExternalStorageDirectory()+File.separator+"yourAppDir");
if(!yourAppDir.exists() && !yourAppDir.isDirectory())
{
// create empty directory
if (yourAppDir.mkdirs())
{
Log.i("CreateDir","App dir created");
}
else
{
Log.w("CreateDir","Unable to create app dir!");
}
}
else
{
Log.i("CreateDir","App dir already exists");
}
you can use this :
File directory = new File(Environment.getExternalStorageDirectory() + "/images");
directory.mkdirs();
Environment.getExternalStorageDirectory() is deprecated. So you should use this:
File directory = new File(this.getExternalFilesDir(null).getAbsolutePath() + "/YourDirectoryName");
directory.mkdirs();
One thing that is worth noting is if you always get false from the mkdirs(), try to unplug your device from pc, and see if it could create folders. At least I tried, it worked for me, currently I'm looking for ways to fix this problem.
To create specific root directory and its sub folder i use this code
String root = Environment.getExternalStorageDirectory().toString();//get external storage
File myDir = new File(root + "/grocery"+"/photo/technostark");//create directory and subfolder
File dir=new File(root + "/grocery"+"/data");//create subfolder
myDir.mkdirs();
dir.mkdirs();
To create file inside sd card you have to use Environment.getExternalStorageDirectory()
/**
* Creates a new directory inside external storage if not already exist.
*
* #param name The directory name
*/
public static void createNewDirectory(String name) {
// create a directory before creating a new file inside it.
File directory = new File(Environment.getExternalStorageDirectory(), name);
if (!directory.exists()) {
directory.mkdirs();
}
}
Following two important parameter which helps you to create directory
1. directory.mkdirs() :
Creates the directory named by this file, creating missing parent
directories if necessary.
2. directory.mkdir() :
Creates the directory named by this file, assuming its parents exist.
For more you can how getExternalStorageDirectory() works please see link
This should help.
First get the path of the external storage:
File root=Environment.getExternalStorageDirectory();
Then:
File picDirectory = new File(root.getAbsolutePath(), "mnt/sdcard/images");
picDirectory.mkdirs();