Search code examples
scalajarnio

How to list all files from resources folder with scala


Assume the following structure in your recources folder:

resources
├─spec_A
| ├─AA
| | ├─file-aev
| | ├─file-oxa
| | ├─…
| | └─file-stl
| ├─BB
| | ├─file-hio
| | ├─file-nht
| | ├─…
| | └─file-22an
| └─…
├─spec_B
| ├─AA
| | ├─file-aev
| | ├─file-oxa
| | ├─…
| | └─file-stl
| ├─BB
| | ├─file-hio
| | ├─file-nht
| | ├─…
| | └─file-22an
| └─…
└─…

The task is to read all files for a given specification spec_X one subfolder by one. For obvious reasons we do not want to have the exact names as string literals to open with Source.fromResource("spec_A/AA/…") for hundreds of files in the code.

Additionally, this solution should of course run inside the development environment, i.e. without being packaged into a jar.


Solution

  • Thanks to @TrebledJ ’s answer, this could be minimized to the following:

    class ConfigFiles (val basePath String) {
      lazy val jarFileSystem: FileSystem = FileSystems.newFileSystem(getClass.getResource(basePath).toURI, Map[String, String]().asJava);
    
      def listPathsFromResource(folder: String): List[Path] = {
        Files.list(getPathForResource(folder))
          .filter(p ⇒ Files.isRegularFile(p, Array[LinkOption](): _*))
          .sorted.toList.asScala.toList // from Stream to java List to Scala Buffer to scala List
      }
    
      private def getPathForResource(filename: String) = {
        val url = classOf[ConfigFiles].getResource(basePath + "/" + filename)
        if ("file" == url.getProtocol) Paths.get(url.toURI)
        else jarFileSystem.getPath(basePath, filename)
      }
    }
    

    special attention was necessary for the empty setting maps.

    checking for the URL protocol seems inevitable. Git updated, PUll requests welcome: https://github.com/kurellajunior/list-files-from-resource-directory