scala 如何在scala中使用相对路径读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31453511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a text file using Relative path in scala
提问by ka4eli
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.
我有一个用 Scala 编写的简单 mvn 项目。我想访问一个文本文件并阅读其内容。代码工作正常,但唯一的问题是我在读取文本文件时给出了绝对路径。以下是我的项目的目录结构。
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?)
如何使用相对路径读取该文件?(我是否必须将 movies.txt 文件移动到资源目录中,如果是这样,我将如何读取该文件?)
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.
在其中 Simulate 是包对象的 myobject.scala 中,我使用绝对路径访问movies.txt 文件。
import scala.io.Source
Source
.fromFile("/home/eshan/projecs/myproject/movies.txt")
.getLines
.foreach { line =>
count+=1
// custom code
}
回答by ka4eli
Move your movies.txtto resourcesdir, then you can do the following:
移动您movies.txt的resources目录,然后您可以执行以下操作:
val f = new File(getClass.getClassLoader.getResource("movies.txt").getPath)
import scala.io.Source
Source
.fromFile(f)
.getLines
.foreach { line =>
count+=1
// custom code
}
回答by Gids
More concisely you can use:
更简洁地您可以使用:
Source.fromResource("movies.txt")
which will look for a path relative to the resources folder.
它将查找相对于资源文件夹的路径。

