In my application, when a user want to upload Audio, that user should only be able to choose .mp3 extension file. If the user choose any other file like .ppt, .pdf, it wont be allowed.
I have got this approved code for File explore from SD Card: Choose file dialog.
But I want only .mp3 extension files or list of .mp3 extension files.
So what should I do?
maybe you can check for files like this
File f = new File("/sdcard/");
for (File file : f.listFiles())
{
if(file.getName().endsWith(".mp3"))
{
// do something with them, add them to list or whatever
}
}
Check file pattern and then compare, if it is mp3 then add into arraylist, check below function, which will return list of mp3.
Vector<String> mStrings =new Vector<String>();
int mTotalimage=0;
public void fileExtension(File dir) {
String mp3Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
String mCheck=listFile[i].getAbsoluteFile().toString();
mCheck=mCheck.substring(mCheck.lastIndexOf("/")+1);
System.out.println("listFile[i].getAbsoluteFile().toString()"+listFile[i].getAbsoluteFile().toString());
System.out.println("mCheck..."+mCheck);
if (listFile[i].isDirectory() && !(mCheck.startsWith(".")) ) {
fileExtension(listFile[i]);
} else {
//fetch jpg from folders.
if (listFile[i].getName().endsWith(mp3Pattern)){
mStrings.add(listFile[i].getAbsolutePath().toString());
mTotalimage++;
//fetch png image from folders.
}
}
}
}
System.out.println("size on return......."+mStrings.size());
}
Related
I am building an Android app that writes files in the format of my custom .fire extension.
I need to access them all at once and put them in a ListView. Could someone please help me to fetch them via an activity or Async Task Manager?
You can write an Async Task to fetch the .fire files from the folder into which you are writing them initially and dynamically add the filenames into the listview.
You can do something like this in your async task:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/"+FolderWhichContainsyourFiles);
File[] listOfFiles = dir.listFiles();
for (int count = 0; count < listOfFiles.length; count++) {
File file = listOfFiles[count];
if (file.isFile() && file.getName().endsWith(".fire")) {
String fileName = file.getName();
//Here you can dynamically add this name into the ListView
}
}
}
You need to use an ArrayAdapter and add elements to the ArrayAdapter dynamically. It is brilliantly explained here: Dynamically add elements to a listView Android
if you want to find files recursively:
private static List<File> filesList = new ArrayList<File>();
public static List<File> recursiveList(String filePath) {
try {
File[] dir = new File(filePath).listFiles();
for (File item : dir) {
if (item.isDirectory()) recursiveList(item.getAbsolutePath());
else if (item.isFile() && item.getName().endsWith(".fire"))
filesList.add(item);
}
return filesList;
} catch (Exception e) {
return null;
}
}
and to retrieve files in activity:
List<File> files = recursiveList("/sdcard/Music/");
for (File file : files)
adapterFilesList.add("" + file.getName());
I have a variable "directorypath". It has the path to a directory in sd card.
Ex: "sdcard/images/scenes"
Now, I want to list all the files in the "directorypath" and want an Array to store all the file names in it.
Ex: Array[0]= Filename1, Array[1]= Filename2 Etc...
I tried something like Array[] myArray = directorypath.listfile(); but didn't work..!
Can anyone give me the code or at least help me? Much appreciated.
I think the problem you are facing is related to the external storage directory file path. Don't use whole path as variable if you can access with environment.
String path = Environment.getExternalStorageDirectory().toString()+"/images/scenes";
Also, you can use the API listfiles() with file object and it will work. For eg ::
File f = new File(path);
File file[] = f.listFiles();
Try the following code which may help you
List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
inFiles.add(file);
}
}
return inFiles;
}
This will return you list of files under the directory you specified.
From the File object in list.. you will get all information about files you required.
Try the following code:
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File folder = new File(externalStorageDirectory.getAbsolutePath() + "/FilePath");
File file[] = folder.listFiles();
if (file.length != 0) {
for (int i = 0; i < file.length; i++) {
//here populate your list
}
} else {
//no file available
}
According to your error message "Cannot resolve listFiles()", you are trying to call a method on a String object, when you actually want to be calling that on a File object.
Create a new File object,
String parentDirectory = "path/to/files";
File dirFileObj = new File(parentDirectory);
File[] files = dirFileObj.listFiles();
I was indeed calling a function for improper data type. i.e., listfiles() won't work on String type variable..!!
SO, I created a File type variable and a File[] array to pass the list of files..!
This solved the issue.
its very simple Just two lines of code
File mListofFiles = new File(Environment.getExternalStorageDirectory.getAbsolutePath()+"/",childpath:Foldername);
File f = new File(mListofFiles.toString());
File file[] = f.listFiles();
I am trying to program my own file manager for android. What I want to know is that how can I read the file names of all the files present in external/internal storage?
I want to read the file names and show them in a listview so the user could see what files are present in what folder. I know this thing is going to work in recursive manner as I have to read the content of sub directories as well.
This is what you have to do. Before going to write please refer the File class in java. This will help you to clear lot of things.
Below is the snippet that provides the list of files.
File directory = new File(path);
File[] listFiles = directory.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
if (file.isDirectory())
// do the stuff what you need
else if (file.isFile()) {
// do the stuff what you need
}
}
}
}
Following code will give you list of files in android sdcard:
/**
* Return list of files from path. <FileName, FilePath>
*
* #param path - The path to directory with images
* #return Files name and path all files in a directory, that have ext = "jpeg", "jpg","png", "bmp", "gif"
*/
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg",
"png", "bmp", "gif");
#Override
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
You can call same method to get sub directory file also.
I want to list of the Text file in Listview and Select .txt file path get from the sdcard.
Try this :
public void scandir(File dir) {
String txtPattern = ".txt";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
scandir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(txtPattern)){
//Do what ever u want
}
}
}
}
}
Make a call like this:
scandir(Environment.getExternalStorageDirectory());
Reference :
Android List documents with Specific extension from SD Card
Use .endsWith() method from Java String Class to check File Extension from file path.
you can see my answer here
(another option)
You can use FilenameFilter Interface to Shortlist all TextFiles are any related files to an Array. check this answer here to shortlist only image files from SD card.
I need to calculate the number of images stored in SD card and so i would like to name the images unique like Sample0,Sample1,Sample2,Sample3,etc.
Is it Possible?
It gives the number of images present in the images folder of your SD card:
File dir = new File(Environment.getExternalStorageDirectory()
+ "/images");
File[] files = dir.listFiles();
int numberOfImages=files.length;
I now it's been a long time, but, the method above would give you the number of any kind of files and directories within images folder, not only the images number, and doesn't look for images in subfolders inside the images directory.
Let's say we have this structure:
Images/
- img1.jpg
- img2.jpg
- data.dat
- whatever.pdf
- Folder/
- img3.png
The method above will give you 5 and you should obtain 3 isn't it?
I've been working on something similar and I'm pretty sure there is a more efficient way, but with this method I get the number of all images within the SDCard, or any given directory and its subfolders...
Here we go:
public int countImgs(File file, int number) {
File[] dirs = file.listFiles();
String name = "";
if (dirs != null) { // Sanity check
for (File dir : dirs) {
if (dir.isFile()) { // Check file or directory
name = dir.getName().toLowerCase();
// Add or delete extensions as needed
if (name.endsWith(".png") || name.endsWith(".jpg")
|| name.endsWith(".jpeg")) {
number++;
}
} else number = countImgs(dir, number);
}
}
return number;
}
Where the param file is the root directory and the number would be 0 at start. So to use it:
int imgNumber = countImgs(Environment.getExternalStorageDirectory(), 0);
it will be an error when files = null when get the count of images stored in SD card
File dir = new File(Environment.getExternalStorageDirectory() + "/images");
File[] files = dir.listFiles();
String strnumberOfImages=files.length;
int intnumberOfImages= 0;
try{
intnumberOfImages = Integer.parseInt( strnumberOfImages);
}catch ( Exception e ){
intnumberOfImages = 0;
}
if just check empty or not
File dir = new File(Environment.getExternalStorageDirectory()+ "/images");
File[] files = dir.listFiles();
if(files != null){
// there are picz
}else{
// sd card empty
}