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());
Related
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.
I am using json to get the image from url and successfully stored into sdcard.
I want to get image from sdcard and display into gridview. when I am using below code I can easily get the all image and easily display into grid view.
public void getFromSdcard() {
ArrayList<String> f = new ArrayList<String>();
File file = new File("/mnt/sdcard/IMG");
if (file.isDirectory()) {
listFile = file.listFiles();
Log.v("Length", "IMG ::" + listFile.length);
for (int i = 0; i < listFile.length; i++) {
f.add(listFile[i].getAbsolutePath());
}
}
}
The problem is I don't want to display all the images into grid view, i want to display specific images (using image prefix).
for example i have list of jpg below
LR-001.jpg
LR-002.jpg
GR-001.jpg
GR-002.jpg
CF-001.jpg
CF-002.jpg
ER-001.jpg
ER-002.jpg
GBR-001.jpg
GBR-002.jpg
GPT-001.jpg
GPT-002.jpg
NCK-001.jpg
NCK-002.jpg
how to get image of GR prefix?
You could check if the filename starts with "GR" for instance:
for (int i = 0; i < listFile.length; i++) {
String fileName = listFile[i].getName();
if (fileName.startsWith("GR"))
f.add(listFile[i].getAbsolutePath());
}
the same with the for-each
for (File file : listFile) {
String fileName = file.getName();
if (fileName.startsWith("GR"))
f.add(file);
}
to get a random entry from your ArrayList you can use the class Random
private Random randomGenerator;
randomGenerator = new Random();
int index = randomGenerator.nextInt(f.size());
File file = f.get(index);
nexInt returns a number between 0 and f.size() - 1
You could check your filenames for the starting letters "GR"
Following Code should work
List<File> f = new ArrayList<File>();
File file = new File("/mnt/sdcard/IMG");
if (file.isDirectory()) {
listFile = file.listFiles();
Log.v("Length", "IMG ::" + listFile.length);
for (File file : listFile) {
if(file.getName().startsWith("GR"){
f.add(file.getAbsolutePath());
}
}
}
Hope it will help you
You could use a FilenameFilter:
f = file.list(new FilenameFilter(){
#Override
public boolean accept(File dir, String filename){
if (filename.startsWith("GR")) return true;
return false;
}
});
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);
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";
}
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 ");
}
}