android find external folders through mnt - android

Let me get this out of the way; I am a beginner to java, I research the code I need and try to learn it while using it in my app.
I am currently stuck, not really sure how I can continue, ANY help is greatly appreciated.
I am trying to look in the /mnt/ folder for any folder with 'ext' or 'sd' in the file name. This is what I have so far, it gets me a null pointer exception but I don't know what variable is null.
public class MainActivity extends Activity
{
static File[] dirs;
#Override
public void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findMnt("/mnt/");
AlertDialog builder = new AlertDialog.Builder(this).setTitle("AppName").setMessage(dirs[0].getPath()).setNeutralButton("Close", null).show();
AlertDialog builder2 = new AlertDialog.Builder(this).setTitle("AppName").setMessage(dirs[1].getPath()).setNeutralButton("Close", null).show();
}
public static void findMnt(String path) {
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("sd") || list[i].getPath().contains("ext")){
for(int b=0; b<list.length; b++){
dirs[b] = new File(list[i].getPath());
}
}
}
}
}
}

Memory Cases: if you take any new device or for ex. micromax funbook, then its having three memory
/data/data/ (phone internal memory) getFilesDirectory()
/mnt/sdcard/ (phone's internal sdcard)
Environment.getExternalStorageDirectory()
/mnt/extsd/ (External sdcard) /mnt/extsd
You first need to be sure whether your External card is of /mnt/sdcard/ or /mnt/extSd for that I have created a function
/**
* #return Number of bytes available on external storage extSD
*/
public long getExternalAvailableSpaceInBytes() {
long availableSpace = -1L;
try {
StatFs stat = new StatFs("mnt/extsd");
System.out.println("ExternalAvailableSpace Path : "+mStringExernalSD);
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
} catch (Exception e) {
e.printStackTrace();
}
return availableSpace;
}
if getExternalAvailableSpaceInBytes() returns 0 it means you need to consider /mnt/sd
To get all folders
ArrayList<File> mFiles= new ArrayList<File>();
if(getExternalAvailableSpaceInBytes()>0)
findMnt(mFiles, "/mnt/extsd");
else
findMnt(mFiles, "/mnt/sdcard");
public ArrayList<File> findMnt(ArrayList<File> files, File dir)
{
if (!dir.isDirectory())
{
files.add(dir);
return files;
}
for (File file : dir.listFiles())
findMnt(files, file);
return files;
}

This method is crude but will work for what I need it to. Searches for the sdcard folder, then searches for a folder with ext in the name, and if it fails it searches the sdcard folder for an ext folder.
String sd = findSd("/mnt/") + "/";
String ext = findExt("/mnt/") + "/";
if(ext == "ext not found"){
ext = findExt(sd + "/");
}
public static String findSd(String path){
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("sd")){
return list[i].getPath();
}
}
}
}
return "sd not found";
}
public static String findExt(String path){
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("ext") && list[i].getPath() != findSd("/mnt/")){
return list[i].getPath();
}
}
}
}
return "ext not found";
}

Related

Why is listFiles() method returning null?

I'm wondering why the listFiles() method is returning null? I am using the this string for a file path: /storage/UsbDriveA.
Here is the code I'm currently using:
List<String> filesInFlashDrive = addListOfFiles("/storage/UsbDriveA/");
public ArrayList<String> addListOfFiles(String directoryPath) {
File f = new File(directoryPath);
f.mkdirs();
Log.i("FileBrowserActivity", "File Value:" + f);
Log.i("FileBrowserActivity", "List of files:"+f.listFiles());
File[] file = f.listFiles();
/*File[] file = f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.toString().endsWith(".pdf") ? true : false;
}
});*/
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
Why is the listFiles() method returning null?
First, your device or emulator may not have such a path. Very few devices do.
Second, because that appears to be removable storage, you do not have arbitrary filesystem access to it on Android 4.4+ devices.

External SDCard file path for Android

Is it true that the file path to external SDCard on Android devices are always "/storage/extSdCard"? If not, how many variations are there?
I need it for my App to test the availability of external SDCard.
I am using Titanium, it has a method Titanium.Filesystem.isExternalStoragePresent( )
but it always return true even external SDCard is not mounted.
I think it detect SDCard at local storage thus return true. But what I really want is detect whether physical SDCard is mounted or not.
Can I do this by detecting the existence of file "/storage/extSdCard" alone?
Thanks.
Is it true that the file path to external SDCard on Android devices are always "/storage/extSdCard"? If not, how many variations are there?
Sadly the path to the external storage is not always the same according to manufacturer. Using Environment.getExternalStorageDirectory() will return you the normal path for SD card which is mnt/sdcard/. But for Samsung devices for example, the SD card path is either under mnt/extSdCard/ or under mnt/external_sd/.
So one way to proceed would be to check the existence of external directory according to the path used by each manufacturer. With something like this:
mExternalDirectory = Environment.getExternalStorageDirectory()
.getAbsolutePath();
if (android.os.Build.DEVICE.contains("samsung")
|| android.os.Build.MANUFACTURER.contains("samsung")) {
File f = new File(Environment.getExternalStorageDirectory()
.getParent() + "/extSdCard" + "/myDirectory");
if (f.exists() && f.isDirectory()) {
mExternalDirectory = Environment.getExternalStorageDirectory()
.getParent() + "/extSdCard";
} else {
f = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/external_sd" + "/myDirectory");
if (f.exists() && f.isDirectory()) {
mExternalDirectory = Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/external_sd";
}
}
}
But what I really want is detect whether physical SDCard is mounted or not.
I didn't try the code yet, but the approach of Dmitriy Lozenko in this answer is much more interesting. His method returns the path of all mounted SD cards on sytem regardless of the manufacturer.
This is how I finally got sdcard path using :
public String getExternalStoragePath() {
String internalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String[] paths = internalPath.split("/");
String parentPath = "/";
for (String s : paths) {
if (s.trim().length() > 0) {
parentPath = parentPath.concat(s);
break;
}
}
File parent = new File(parentPath);
if (parent.exists()) {
File[] files = parent.listFiles();
for (File file : files) {
String filePath = file.getAbsolutePath();
Log.d(TAG, filePath);
if (filePath.equals(internalPath)) {
continue;
} else if (filePath.toLowerCase().contains("sdcard")) {
return filePath;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
if (Environment.isExternalStorageRemovable(file)) {
return filePath;
}
} catch (RuntimeException e) {
Log.e(TAG, "RuntimeException: " + e);
}
}
}
}
return null;
}
I hope it will be useful for you :)
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class MemoryStorage {
private MemoryStorage() {}
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if (mountFile.exists()) {
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if (voldFile.exists()) {
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for (String mount : mMounts) {
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if (list != null) {
for (File f : list) {
hash += f.getName().hashCode() + ":" + f.length() + ", ";
}
}
hash += "]";
if (!mountHash.contains(hash)) {
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if (map.isEmpty()) {
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
}
I just figured out something. At least for my Android Emulator, I had the SD Card Path like ' /storage/????-???? ' where every ? is a capital letter or a digit.
So, if /storage/ directory has a directory which is readable and that is not the internal storage directory, it must be the SD Card.
My code worked on my android emulator!
String removableStoragePath;
File fileList[] = new File("/storage/").listFiles();
for (File file : fileList)
{ if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead())
removableStoragePath = file.getAbsolutePath(); }
//If there is an SD Card, removableStoragePath will have it's path. If there isn't it will be an empty string.
If there is an SD Card, removableStoragePath will have it's path. If there isn't it will be an empty string.
I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):
Use path for internal storage String
path="/storage/sdcard0/myfile.txt";
use path for external storage
path="/storage/sdcard1/myfile.txt";
mention permissions in Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
First check file length for confirmation.
Check paths in ES File Explorer regarding sdcard0 & sdcard1 is
this same or else...
e.g.:
File file = new File(path);
long = file.length();//in Bytes

Filtering files in a directory on Android

In my app i am getting the images from a folder in gallery and saving it into an array list.Now i want to extract only the files with .jpg extension.How can i do it
The code for saving to array list is
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
tFileList.add(file.getPath());
}
return tFileList;
}
You can use FilenameFilter interface to Filter the Files.
Change your codeline
File[] files=f.listFiles();
as below:
File[] jpgfiles = f.listFiles(new FileFilter() {
#Override
public boolean accept(File file)
{
return (file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg"));
}
});
Use .endsWith() method from Java String Class to check File Extension from file path.
Method:
public boolean endsWith(String suffix)
Your Code something like,
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
String filePath = file.getPath();
if(filePath.endsWith(".jpg")) // Condition to check .jpg file extension
tFileList.add(filePath);
}
return tFileList;
}
private List<String> ReadSDCard()
{
String extension = "";
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
int ind = files[i].getPath().lastIndexOf('.');
if (ind > 0) {
extension = files[i].getPath().substring(i+1);// this is the extension
if(extension.equals("jpg"))
{
tFileList.add(file.getPath());
}
}
}
return tFileList;
}
In your code add the following:
String filePath = file.getPath();
if(filePath.endsWith(".jpg"))
tFileList.add(filePath);

Get count of total media file available in sdcard folder?

How can get total count of available media file in sdcard/some/ folder that should include audio, images, video.
I think something like this
File file=new File("/sdcard/domedir");
File[] list = file.listFiles();
int count = 0;
for (File f: list){
String name = f.getName();
if (name.endsWith(".jpg") || name.endsWith(".mp3") || name.endsWith(".some media extention"))
count++;
}
Maybe you should write a simple recursive method like this one :
public int countFile(String path) {
int count = 0;
File f = new File(path);
if (f.exists() && f.isDirectory()) {
for (File fi : f.listFiles()) {
if (fi.isDirectory())
count += countFile(fi.getAbsolutePath());
else
count++;
}
}
return count;
}
Well you can simply check whether the type of files correspond to common media types
static class MyDocFileFilter implements FileFilter{
private final String[] myDocumentExtensions
= new String[] {".java", ".png", ".avi", ".mkv"};
public boolean accept(File file) {
if (!file.isFile()) return false;
for (String extension : myDocumentExtensions) {
if (file.getName().toLowerCase().endsWith(extension))
return true;
}
return false;
}
}
Then use File to list all the required files using the filter. And change extensions accordingly
File file = new File("DIRECTORY_NAME");
File[] fileslist = file.listFiles(new MyMediaFileFilter());

How to list all the files in a custom Directory

I'm trying to list all the files in a directory I have made, when I create the directory I warp a file for each contact into the dir. I then want to be able to list all those files inside/within the directory. I have tried everything including
String a = listFiles().tostring();
Yet, nothing happens. To sum it up, I want to list all the files within a custom dir in the SD card.
Here's my updated code
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
String read = path.getbytes().tostring();
You have to see this tutorial how to build an android file browser it will help you a lot!!
This one list all folder and files in sdcard you can adapt it to what you need by changing the value of currentDir in the code
This code is travel entire sdcard and list files. that's may be helpful to you ..!
import java.io.*;
import java.util.*;
public class DirUtils {
public static List recurseDir(String dir) {
String result, _result[];
result = recurseInDirFrom(dir);
_result = result.split("\\|");
return Arrays.asList(_result);
}
private static String recurseInDirFrom(String dirItem) {
File file;
String result,list[];
result = dirItem;
file = new File(dirItem);
if (file.isDirectory()) {
list = file.list();
File[] fileslist = file.listFiles(new MyDocFileFilter());
if (fileslist != null) {
for (File file1: fileslist) {
System.out.println(file1.getAbsolutePath());
}
}
else {
System.out.println("No Subdirectory Found.");
}
for (int i = 0; i < list.length; i++)
result = result + "\n" + recurseInDirFrom(dirItem + File.separatorChar + list[i]);
}
return result;
}
static class MyDocFileFilter implements FileFilter
{
private final String[] myDocumentExtensions
= new String[] {".java", ".png", ".html", "class"};
public boolean accept(File file) {
if (!file.isFile())
return false;
for (String extension : myDocumentExtensions) {
if (file.getName().toLowerCase().endsWith(extension))
return true;
}
return false;
}
}
public static void main(String arg[]) {
DirUtils.recurseDir("your path ");
}
}

Categories

Resources