简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM