开发者

How can I access a resource when running an SBT runTask?

开发者 https://www.devze.com 2023-03-15 17:52 出处:网络
I\'ve got an XML file that I need to read from the classpath in order to load some test data for my project with DBUnit when running a custom runTask in SBT.

I've got an XML file that I need to read from the classpath in order to load some test data for my project with DBUnit when running a custom runTask in SBT.

The XML file is located in /src/main/resources and is copied properly to the /target/scala_2.8.1/classes during the build,开发者_JAVA百科 but I get a MalformedURLException when trying to access it.

The weird thing is, I can access the file when this data loading functionality was part of my Scala specs unit tests.

Any ideas?


In my case the problem was that I used getClass.getResourceAsStream() in early initialiser. Had to specify the class explicitly with Class.forName() to solve it: Class.forName(<class name>).getResourceAsStream("/data.xml")


If the error is saying that the URL is malformed, it's probably true. Here's a code I use to grab file from resource during test:

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: String = null
  line = reader.readLine
  while (line != null) {
    out.println(line)
    line = reader.readLine
  }
  in.close
  out.flush
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号