user4700203
user4700203

Reputation:

How to read a text file using Relative path in scala

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            
}

Upvotes: 8

Views: 22387

Answers (3)

Powers
Powers

Reputation: 19328

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.

Upvotes: 1

Gids
Gids

Reputation: 752

More concisely you can use:

Source.fromResource("movies.txt") 

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

Upvotes: 5

ka4eli
ka4eli

Reputation: 5424

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            
}

Upvotes: 9

Related Questions