Scala: How to get file list inside resources?

Sometimes it is necessary to list all files, or files with specific suffix, inside resources.

It should work for file system in the develop stage as well for JAR in production.

A solution is fileNames method:

/**
  * Searches in the resources a list of file names matching a file name suffix
  *
  * @param fileNameSuffix the file name suffix; empty - all files
  * @param folder         specifies a folder; default value is "."
  * @return the list of file names matching a file name suffix
  */
def fileNames(fileNameSuffix: String, folder: String = "."): Seq[String] = {
  new File(Thread
    .currentThread()
    .getContextClassLoader
    .getResource(folder)
    .getPath)
    .listFiles(new FileFilter {
      override def accept(pathname: File): Boolean = {
        pathname.isFile && pathname.getName.endsWith(fileNameSuffix)
      }
    })
    .map(file => file.getName)
}

Code source is here: https://github.com/ysden123/ys-scala-tools/blob/master/src/main/scala/com/stulsoft/scala/tools/resources/ResourceUtils.scala

Advertisements

About ysden123

We are not only for work... All my time free from work I spend on photography. Most photos are from our travels. I like make photos in still life style as well.
This entry was posted in Programming, Scala and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.