list the files from internal storage android - android

I am currently working with internal storage
i have some problems,
I am also get the files in particular folder on internal storage,but my list shows all root folders like data/data/com.example.app/sample.mp4, But i want only filename like sample.mp4.
Here my code
`
ArrayList<File> fileList = new ArrayList<File>();
File mydir = this.getDir("Myfolder", Context.MODE_PRIVATE);
File listFile[] = mydir.listFiles();
if (listFile != null && listFile.length > 0) {
for (File aListFile : listFile) {
if (aListFile.isDirectory()) {
fileList.add(aListFile);
} else {
if (aListFile.isFile());
{
fileList.add(aListFile);
}
}
}`

Get filename from file object
if (aListFile.isFile());
{
string fileName = aListFile.getName();
}

try this one,
YourFilePath.substring(YourFilePath.lastIndexOf("/")+1)
For example,
String filePath = "data/data/com.example.app/sample.mp4"
String fileName = filePath.subString(filePath.lastIndexOf("/")+1);
And finally you get your fileName = sample.mp4

Related

Activity to search all music files (or a particular extension) in Android storage

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());

How to read file names of the files that are present in the android's Internal/External storage

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.

How to access all 3GP audio files from SDcard

This is how i tried to access files from SDcard
// Use the current directory as title
path = "/sdcard/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
final List values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
final String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (!file.startsWith(".")) {
values.add(file);
}
}
}
Collections.sort(values);
but not getting how to display only 3Gp vales in list ,anyone suggest me to how to do it.
Thank you.
Have you tried just checking to see if the file has a .3gp extention?
Like:
if(file.contains(".3gp"))?

Android How do I check the number of files in a directory

I am creating a directory in internal memory of device for storing files for application use.I am using:
File dir = context.getDir(userfavorites, Context.MODE_PRIVATE);
The above code will create a new directory if it does not exists or returns me the existing file object if directory has already been created.What I want to check is the number and name of files this directory contains.How do I use this file object to accomplish this task.
NOTE:I don't want to use external memory of device.And I can't avoid creating directory as well because the files in directory has to be separated from other files that are not in directory.
UPDATED CODE:
private static boolean IsFoldercontainsFiles(Context context) {
// TODO Auto-generated method stub
File dir = context.getDir(USER_FAV, Context.MODE_PRIVATE);
if (dir.exists()) {
if (dir.listFiles() == null){
return false;} //it never execute this line even though its null
else{
File childfile[] = dir.listFiles();
Log.i("file no is ", Integer.toString(childfile.length));
if (childfile.length == 0) {
return false;
} else {
return true;
}
}
} else {
return false;
}
}
Thanks in advance
Check the listFiles method of File that will give you the list of children.
File file=new File("/mnt/sdcard/yourfolder");
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++;
System.out.println("170 " + count);
}
try this
File childfile[] = dir .listFiles();
for (File file2 : childfile) {
Log.v("file name is ", file2.getName());
}
here listFiles() return all the childfiles for the "dir" and iterating this will help you to get the names of the childfiles
Simple:
File dir = new File(path); // "/mnt/sdcard/yourfolder"
long totalNumFiles = dir.listFiles().length;
Try this sample of code for getting number of files in a directory
private int getNumberOfFiles() throws FileNotFoundException {
File outFile = new File(outFolder);
if (!outFile.exists())throw new FileNotFoundException();
int numberofFiles = outFile.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return (file.getPath().startsWith("frame_")&&(file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg")));
}
}).length;
return numberofFiles;
}
The listFiles method of the File class returns an array of File objects, one for each file or directory in the directory.
One can use recursion to find all files within a directory and its subdirectories.
fun File.getFileCountRecursively(): Int {
var fileCount = 0
if (exists() && isDirectory) {
listFiles()?.forEach { child ->
fileCount += if (child.isDirectory) child.getFileCountRecursively() else 1
}
}
return fileCount
}

Get filenames from a directory in Android

I want to populate a spinner with the filenames of files found on the SD card with specific extensions. I can get it thus far to populate the spinner with the correct files, but the path is shown as well.
Can anyone tell me how to only get the filename of a specific file in a directory on the SD card?
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "path");
for (File f : yourDir.listFiles()) {
if (f.isFile())
String name = f.getName();
// Do your stuff
}
Have a look at Environment page for more info.
Try below code
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard, "yourpath");
for (File f : dir.listFiles()) {
if (f.isFile())
String name = f.getName();
// do whatever you want with filename
}
File filePath= new File(File Address);
File[] fileList = filePath.listFiles();
String name = fileList [0].getName().toString();
could you process the string in reverse order(right to left), finding the first slash, then cutting the string at that point and taking the rightmost part of the string as the filename ?
use method getName() of file object:
file.getName();
Above answers are giving null pointer exception in my case. Following code worked for me:
File yourDir = new File(Environment.getExternalStorageDirectory().getPath() + "/WhatsApp/Databases");
for (File f : yourDir.listFiles()) {
if (f.isFile())
name = f.getName();
// Do your stuff
}

Categories

Resources