8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ScalaAdvent Calendar 2022

Day 12

Scala(Java)でresourcesフォルダ内のファイル一覧を取得する方法

Last updated at Posted at 2015-11-25

resourcesフォルダ内にregressionというフォルダが有りその中のファイル一覧を取得したい場合以下のようにします(jarファイル化した場合でも使えます)。

val uri = getClass.getResource("/regression/").toURI
var myPath: Path = null

if (uri.getScheme == "jar") {
	val fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap[String, Object]())
	myPath = fileSystem.getPath("/regression/");
} else {
	myPath = Paths.get(uri);
}

val walk = Files.walk(myPath, 1)
val it = walk.sorted().iterator()
it.next()//最初の一つ目はregressionフォルダ自体なので飛ばす
while (it.hasNext) {
	val path = it.next()
	println(path.toAbsolutePath.toString)
}

2015/12/07追記
FileSystems.newFileSystem関数は全く別の場所でも2回実行されるとjava.nio.file.FileSystemAlreadyExistsExceptionというエラーが起きてしまうので、一つテキトーなパスでfileSystem変数を作ったらそれを使いまわさなければいけないようです。

参考リンク
java - How do I list the files inside a JAR file? - Stack Overflow

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?