8

I have a simple mvn project written in scala. I want to access a text file and read its content. The code is working fine but the only issue is I am giving the absolute path when reading the text file. Following is the directory structure of my project.

How can I use the relative path to read that file? (Do I have to move the movies.txt file in to the resources directory, if so still how would I read that file?)

Any insight will be much appreciated. Thank you

myproject
|-src
|  |-resources
|  |-scala
|      |-movies.simulator
|           |-Boot
|           |-Simulate
|                |-myobject.scala
|                      |Simulate
|
|-target
|-pom.xml
|-README
|-movies.txt

In the myobject.scala where the Simulate is the package object, I access the movies.txt file using the absolute path.

import scala.io.Source
Source
    .fromFile("/home/eshan/projecs/myproject/movies.txt")
    .getLines
    .foreach { line =>
    count+=1
      // custom code            
}
1
  • os-lib is the best modern solution, see my answer for more details. Commented Dec 16, 2020 at 2:33

3 Answers 3

9

Move your movies.txt to resources dir, then you can do the following:

val f = new File(getClass.getClassLoader.getResource("movies.txt").getPath)

import scala.io.Source
Source
    .fromFile(f)
    .getLines
    .foreach { line =>
    count+=1
      // custom code            
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hello, I suppose this will work. I am getting an unrelated error of movies.txt file not being found in target/myproject/lib. Once I fix it I believe your solution will work. Thanks for the quick response.
I had to change the .txt to .conf. (to fix the unrelated issue). Then your solution worked for the movies.conf with the addition of the "import java.io.File" to my scala code. Thanks
i am getting error reference to getClass is ambiguous; it is both defined in class Object and imported subsequently by import sparkSession.implicits._ when I am trying to use your approach, but don't understand why? any idea ?
@Andrey... just use this.getClass instead of just getClass
5

More concisely you can use:

Source.fromResource("movies.txt") 

which will look for a path relative to the resources folder.

Comments

1

os-lib is the best way to read files with Scala.

os.read(os.pwd/"movies.txt")

os-lib also supports relative paths but those shouldn't be needed here.

This lib makes it easy to read files, construct paths, and other filesystem operations, see here for more details.

1 Comment

This library helped me. Thanks. Remember when using os.pwd and the folder is deeper in the filesystem you will need to use "segment" for example: os.pwd/"jsonFolder"/"guitarFolder"/"guitar.json"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.