I want to get the size of free memory on internal/external storage of my device programmatically. I\'m using this piece of code :
StatFs stat = new StatFs(En
It is very easy to find out the storage available if you get internal as well as external storage path. Also phone's external storage path really very easy to find out using
Environment.getExternalStorageDirectory().getPath();
So I am just concentrating on how to find out the paths of external removable storage like removable sdcard, USB OTG(not tested USB OTG as I have no USB OTG).
Below method will give a list of all possible external removable storage paths.
/**
* This method returns the list of removable storage and sdcard paths.
* I have no USB OTG so can not test it. Is anybody can test it, please let me know
* if working or not. Assume 0th index will be removable sdcard path if size is
* greater than 0.
* @return the list of removable storage paths.
*/
public static HashSet getExternalPaths()
{
final HashSet out = new HashSet();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try
{
final Process process = new ProcessBuilder().command("mount").redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1)
{
s = s + new String(buffer);
}
is.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines)
{
if (!line.toLowerCase(Locale.US).contains("asec"))
{
if (line.matches(reg))
{
String[] parts = line.split(" ");
for (String part : parts)
{
if (part.startsWith("/"))
{
if (!part.toLowerCase(Locale.US).contains("vold"))
{
out.add(part.replace("/media_rw","").replace("mnt", "storage"));
}
}
}
}
}
}
//Phone's external storage path (Not removal SDCard path)
String phoneExternalPath = Environment.getExternalStorageDirectory().getPath();
//Remove it if already exist to filter all the paths of external removable storage devices
//like removable sdcard, USB OTG etc..
//When I tested it in ICE Tab(4.4.2), Swipe Tab(4.0.1) with removable sdcard, this method includes
//phone's external storage path, but when i test it in Moto X Play (6.0) with removable sdcard,
//this method does not include phone's external storage path. So I am going to remvoe the phone's
//external storage path to make behavior consistent in all the phone. Ans we already know and it easy
// to find out the phone's external storage path.
out.remove(phoneExternalPath);
return out;
}