In SBT project folders hierarchy I am to put my Scala sources in src/main/scala and tests in src/tests/scala. What am I meant to put into src/main/resources and src/tests/resources?
Asked
Active
Viewed 1.2k times
2 Answers
17
Everything in that directory gets packed into the .jar created when you call package
.
This means you can use it for images, sound files, text, anything that's not code but is used by your code.

Dylan Lacey
- 1,839
- 12
- 23
-
Thank you, Dylan. Can you link to a Scala (2.8) code example on how do I employ these resources then? – Ivan Oct 07 '10 at 23:57
-
1This duplicate question has a concise example: http://stackoverflow.com/questions/5285898/how-to-get-a-resource-within-scalatest-w-sbt – emchristiansen Oct 05 '11 at 00:24
8
Here's an example of copying a text file stored in resource to a local file system:
def copyFileFromResource(source: String, dest: File) {
val in = getClass.getResourceAsStream(source)
val reader = new java.io.BufferedReader(new java.io.InputStreamReader(in))
val out = new java.io.PrintWriter(new java.io.FileWriter(dest))
var line: Option[String] = None
line = Option[String](reader.readLine)
while (line != None) {
line foreach { out.println }
line = Option[String](reader.readLine)
}
in.close
out.flush
}

Eugene Yokota
- 94,654
- 45
- 215
- 319
-
What am I meant to put as "source" argument here? A short name of a file in src/main/resources? I'd like to print a short built-in help file in case a program of mine is called without parameters. So, I've copied your function body, removed dest/out to use just println to print to stdout and used "help.txt" as source. And this gives me a NullPointerException in java.io.Reader.
. – Ivan Nov 12 '10 at 04:45 -
1See http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String) – Eugene Yokota Nov 12 '10 at 11:15
-
1I think this can be shortened using `reader = io.Source.fromInputStream(in).getLines()`, `out = new PrintWriter(dest))`, then all you need is `reader foreach out.println` – Luigi Plinge Sep 12 '11 at 03:15