KaYaK
KaYaK

Reputation: 33

How do i read a folder and display the contents in java.

I'm creating a videogame (textbased) in java, and i need to read a folder to display several .java file names as the savegames. how do i do this? Thanks.

Upvotes: 0

Views: 108

Answers (1)

Eng.Fouad
Eng.Fouad

Reputation: 117665

Use File class, and its methods list() or listFiles():

String folderPath = ...;
for(String fileName : new File(folderPath).list())
{
    if(fileName.endsWith(".java") && fileName.contains("savegames"))
    {
         System.out.println(fileName);
    }
}

Also you can use the same methods with a FilenameFilter, which are list(FilenameFilter filter) or listFiles(FilenameFilter filter):

String folderPath = "";
FilenameFilter filter = new FilenameFilter()
{
    @Override
    public boolean accept(File dir, String name)
    {
        return name.endsWith(".java") && name.contains("savegames");
    }
};

for(String fileName : new File(folderPath).list(filter))
{
    System.out.println(fileName);
}

Upvotes: 3

Related Questions