Question

I need to get a LibGDX FileHandle for every file in a folder. I can do this using

FileHandle [] filehandles;
filehandles=Gdx.files.external("/").list();

to get all the files in a folder. However it doesn't give me sub-folders. I have considered using an if statement in a loop that goes through everything in the folder, checks for subfolders and then lists them too, but id need another array and i cannot be sure how many ill need. Also it would be inefficent.

Was it helpful?

Solution

Here is a recursive solution. I didn't test it but it should work I think:

public void getHandles(FileHandle begin, Array<FileHandle> handles)
{
    FileHandle[] newHandles = begin.list();
    for (FileHandle f : newHandles)
    {
        if (f.isDirectory())
        {
            Gdx.app.log("Loop", "isFolder!");
            getHandles(f, handles);
        }
        else
        {
            Gdx.app.log("Loop", "isFile!");
            handles.add(f);
        }
    }
}

Start it with getHandles(Gdx.file.external("/")). The handler to the root directory.

Just use one Array. Pass it to the method and the method will fill it with all handlers.


UPDATE: You need to call it with the right handle! Since it does matter if you are on an Android device or on the desktop. According to this question Libgdx How to get a list of files in a directory?

Call it like this:

    FileHandle dirHandle;
    if (Gdx.app.getType() == ApplicationType.Android)
    {
        dirHandle = Gdx.files.internal("data");
    }
    else
    {
        dirHandle = Gdx.files.internal("./bin/data");
    }
    Array<FileHandle> handles = new Array<FileHandle>();
    getHandles(dirHandle, handles);

If you use internal. Else use absolute instead of external. If you pass it an empty FileHandle it will not work.

According to the wiki:

Desktop (Windows, Linux, Mac OS X)

On a desktop OS, the filesystem is one big chunk of memory. Files can be referenced with paths relative to the current working directory (the directory the application was executed in) or absolute paths. Ignoring file permissions, files and directories are usually readable and writable by all applications.

Moreover:

External:
External files paths are relative to the SD card root on Android and to the home directory of the current user on desktop systems.

Checked the function with an internal an absolute and also with an external. As mentioned take care that the external is relative to your user directory! e.g. C:/Users/user/... Just pass the right handle to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top