How to read a text file using Relative path in sca

2020-07-15 05:10发布

问题:

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:

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            
}


回答2:

More concisely you can use:

Source.fromResource("movies.txt") 

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



标签: scala maven