Mullefa
Mullefa

Reputation: 1247

Scala IDE: can't read XML file into scala worksheet

New to Scala and having problems reading an XML file in a Scala worksheet. So far I have:

This runs OK, however, when I create the Scala worksheet test_sample_data.sc:

import sample_data.SampleData

object test {
  println(SampleData.data) 
}

I get a java.lang.ExceptionInInitializerError which includes: Caused by: java.io.FileNotFoundException: music.xml (The system cannot find the file specified).

The workspace is C:\eclipse\workspace. Any help or insight much appreciated. Cheers!

UPDATE:

Following aepurniet's advice, I ran new java.io.File(".").getAbsolutePath() and got the following respectively:

So this is what is causing the problem. Does anyone know why this occurs? Absolute file paths resolve the problem. Is this the best solution?

Upvotes: 2

Views: 1783

Answers (1)

Deepti Bhatia
Deepti Bhatia

Reputation: 550

Regarding what is causing different user directory between the scala class and worksheet: You are likely hitting the Eclipse IDE issue listed here
https://github.com/scala-ide/scala-worksheet/issues/102

Jfyi, I used Intellij and the issue is not reproducible there.

Regarding using absolute paths:

Using absolute path works fine for quick testing, but would NOT be a good practice for the actual implementation. You can consider passing the path along with the filename as input to SampleData.

Some hack mentioned here to get the base path of the workspace from the scala worksheet: Configure working directory of Scala worksheet

If this is just for your testing, hacking the absolute path of workspace inside the worksheets might be the easiest for you.

SampleData.scala

package sample_data

import scala.xml.XML

object SampleData {
  def data(filename: String)  = XML.loadFile(filename)
}

object PrintSampleData extends Application {
  println(SampleData.data(System.getProperty("user.dir") + "/music.xml")
}

Scala worksheet:

import sample_data.SampleData

object test {
  val workDir = ... // Using the hack or hardcoding
  println(SampleData.data(workDir + "/music.xml")) 
}

Upvotes: 7

Related Questions