Retrieve all video files from all directories of SD card - java

I'm making a media player. I want to get all videos present in the sd card.
If the video is directly available in top directory of sd card, it is simple. But what about a video file exists in nested directory structure like
directory->directory->directory->file.mp4.
How can I search for a file in a nested directory structure?

You can create a list which can store the location of all the video files present on sd card. Run a loop which will visit every folder and update this array if given file format (in your case video files or .mp4) and add it to array. You can store this list onto persistent storage so as you can read it the next time your application is launched.
Here is sample code which can help you list all files in sdcard
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")) {
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}

With Apache FileUtils:
import org.apache.commons.io.FileUtils;
String path = ...;
String[] extensions = {"mp4", "mov", ...};
Collection<File> allMovies = FileUtils.listFiles(new File(path), extensions, true);

am posting this, maybe it would help some one in need.
as #Jaqen H'ghar said ... i just simplify the code to add the list of the extensions u want to show.
File filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
List<String> fileList = new ArrayList<>();
String[] extensions = {"apk","mp3","mp4","or what ever extension u want"};
Collection<File> allMovies = FileUtils.listFiles(new File(String.valueOf(filePath)), extensions, true);
for (File file: allMovies) {
fileList.add(file.getName());
}

Related

Load image files from internal storage into arrayList

I am busy developing an Android application for university and would like to load all images saved into an internal storage folder into an array list. I have managed to do it using assets but I need to be able to do it using the image files on the internal storage folder that I created
Code used to create the folder
File root_text = Environment.getExternalStorageDirectory();
try {
File folder = new File(Environment.getExternalStorageDirectory() + "/InkousticImages");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
}
Current code used to load asset files into an array list and open them into an inputStream(this is what I want to do but with the files from the internal storage instead)
String[] imageList = getAssets().list("images");
List <String> myList = new ArrayList<>();
for (String filename: imageList) {
if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith("jpeg")) {
myList.add(filename);
}
}
AssetManager assetManager = getAssets()
InputStream istr = assetManager.open("images/" + myList.toArray()[index]);
Any help would be greatly appreciated.
Here, I wrote the code for you, This loops over all the files in the directory and checks if the extension is a valid image and adds the name to the List
List<String> fileNames = new ArrayList<>();
File folder = new File(Environment.getExternalStorageDirectory(), "InkousticImages");
if (!folder.exists()) folder.mkdir();
for (File file : folder.listFiles()) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".jpg") || filename.endsWith("jpeg")) {
fileNames.add(filename);
}
}

Android Studio listFiles returns null with assets folder

In the assets folder I have another folder called songs with .txt files. I've been trying to put all .txt files in a File[ ] but I get a NullPointer on folder.listFiles().
Here's the code :
File folder = new File("assets/songs");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
this.list.add(content);
System.out.println(content);
}
}
return this.list;
Assets are not files on the device. They are files on the development machine. They are entries inside the APK file on the device.
Use AssetManager to work with assets, including its list() method.
As sir #CommonsWare mentioned, you can use AssetManager like this:
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.

Android: path of assets folder for File()?

I have some files in the assets folder of my project, and I want to list them, so I put this in my code:
File dir = new File("com.packagename/assets/fonts");
File[] fileList = dir.listFiles();
Which path should I put to make it work?
I want it so users could install new fonts (I don`t know how to do this yet) so I need to list all the fonts in the folder, including post-installed fonts. If there is any other solutions, please share.
Assets and resources are accessible using file:///android_asset and file:///android_res.
But in this case you will want to do something like this :
Resources res = getResources()
AssetManager am = res.getAssets();
String fileList[] = am.list(dirFrom);
if (fileList != null) {
for ( int i = 0;i<fileList.length;i++) {
Log.d("",fileList[i]);
}
}

java listing the txt files in sub folders

Hi I have a jlist and currently it is viewing a folder + subfolders... Now i would like to change this to view the files in the subfolders as well. below please find the code I am currently using:
jList1.setModel(new javax.swing.AbstractListModel()
{
File folder = new File ("/Assignment_Datex/message_outbox/");
File[] listofFiles = folder.listFiles();
// #Override
public int getSize()
{ return listofFiles.length; }
// #Override
public Object getElementAt(int i)
{ return listofFiles[i];}
}
);
Right now as you can see in the screenshot, the Jlist is only viewing the folders and not the files in them... Any help please?
If you want to show all files and folder under some root folder then you should try someting like this...
Get files and folders under root folder.
Loop over them and check if it is file or folder.
If file then just add to list nothing more.
If folder then add it to list and repeat this same steps for that folder until all folder and files are traveled.
I can not produce whole code here but this is a prototype for this:
void addFilesToList(File folder){
File[] listofFiles = folder.listFiles();
for(File file:listofFile){
if(file.isFile()) // --- file
list.add(file.getName());
else{ // --- folder
addFileToList(file);
}
}
}
The above code is not tested so may need to modify it to fit your need.
#Harry Joy is right.
Additionally you can also use FindFile from jakarta project. It can save your time.
You create a constructor to initialise your class, and there you put (tested and working)
// initialize the class variable
listofFiles = new ArrayList();
// initialize with the path
File f = new File("/home/albertmatyi/Work/python/");
// create a temporary list to work with
LinkedList files = new LinkedList();
// fill it with the contents of your path
files.addAll(Arrays.asList(f.listFiles()));
while (!files.isEmpty()) {
// keep removing elements from the list
f = files.pop();
// if it is a directory add its contents to the files list
if (f.isDirectory()) {
files.addAll(Arrays.asList(f.listFiles()));
// and skip the last if
continue;
}
// check if it's a text file, and add it to listofFiles
if (f.getName().endsWith(".txt"))
listofFiles.add(f);
}
EDIT:
Note:
I've changed the type of listofFiles to ArrayList<File>, which has to be initialized in the constructor using:
listofFiles = new ArrayList<File>();
This allows easier manipulation of the data - no need to manually allocate bigger space for when more text files need to be added
I think this is good way to read all .txt files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
Now you have a list of files that you can do some process on it!

Scan a file folder in android for file paths

So i have a folder at "mnt/sdcard/folder" and its filled with image files. I want to be able to scan the folder and for each of the files that is in the folder put each file path in an arraylist. Is there an easy way to do this?
You could use
List<String> paths = new ArrayList<String>();
File directory = new File("/mnt/sdcard/folder");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
paths.add(files[i].getAbsolutePath());
}
See listFiles() variants in File (one empty, one FileFilter and one FilenameFilter).
Yes, you can use the java.io.File API with FileFilter.
File dir = new File(path);
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File file) {
return file.getAbsolutePath().matches(".*\\.png");
}
};
File[] images = dir.listFiles(filter);
I was quite surprised when I saw this technique, as it's quite easy to use and makes for readable code.

Categories