0

I've written all the complex mumbo jumbo Scala logic but now I am stuck with a very very basic problem. java.io.FileNotFoundException.

I am trying to read from a csv file & feed that data as input to my Code.

My folder structure is:

MainProject 
    AcceptanceTest
        com.myOwn
        nish
            data
                TestData.csv
            pagemodel
            spec
                Test.scala
            util

Here's my file reading piece of code:

import scala.io.Source
class Test { 
val testDataFile = Source.fromFile("./../data/TestData.csv")
for (line <- testDataFile.getLines().drop(1)) {
    val cols = line.split(",").map(_.trim)
    println(s"${cols(0)}|${cols(1)}|${cols(2)}")
}

TestData.csv contains:

#ScenarioName, Value1, Value2
Test1, F1, BrightnessDecrease 
Test2, F2, BrightnessIncrease

Running Test.scala gives me a java.io.FileNotFoundException. If I change my File path to the absolute path, everything works ok.

val testDataFile = Source.fromFile("/MainProject/AcceptanceTest/com/myOwn/nish/data/TestData.csv") 

What is missing in my relative path which I am unable to spot?

Nish
  • 31
  • 6
  • 1
    Are you executing from the command line or from an IDE? You can also println(new java.io.File("./").getCanonicalPath) to better understand the current working folder. – Pascal Soucy Aug 29 '16 at 20:40
  • Thanks Pascal. This helped in figuring out what my working directory was! Finally this worked -> "MainProject/AcceptanceTest/com/myOwn/nish/data/TestData.csv" – Nish Sep 18 '16 at 10:11

3 Answers3

0

Put your csv file inside resources folder (src/main/resources) of the project. now you can access the file inside the resources folder using below code snippet from any where inside the src package. do not forget to put initial /.

Source.fromFile(getClass.getResource("/hello.csv").getFile).getLines().foreach(println)

for more info How to read files from resources folder in Scala?

Community
  • 1
  • 1
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
0

Thank you for all your suggestions. Unfortunately changing the folders structure was not an option, so having a src/main/resource was ruled out (that would probably have been the cleanest solution).

val testDataFile = Source.fromFile("MainProject/AcceptanceTest/com/myOwn/nish/data/TestData.csv")

The current working directory was the MainProject. So a "/" at the beginning was unnecessary. I figured that out using .getCanonicalPath as suggested by Pascal.

Nish
  • 31
  • 6
0

If you are working with an IDE (intellij-idea in my case), and for some reason, you have imported multiple projects as modules, check the working directory in "Run/Debug Configuration". My code could not find the correct path because the source folder of the project was wrong. The way I realized this, was because I used the absolute path.

By the way, I recommend using os-lib by com-lihaoyi from GitHub.

Rodolfo Velasco
  • 845
  • 2
  • 12
  • 27