如何在Scala中使用相对路径读取文本文件 [英] How to read a text file using Relative path in scala
问题描述
我有一个用scala编写的简单的mvn项目.我想访问一个文本文件并阅读其内容.代码工作正常,但是唯一的问题是读取文本文件时我给出了绝对路径.以下是我的项目的目录结构.
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.
如何使用相对路径读取该文件? (我是否必须将movies.txt文件移动到资源目录中,如果还是这样,我将如何读取该文件?)
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
在模拟"是包对象的myobject.scala中,我使用绝对路径访问movie.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
}
推荐答案
将movies.txt
移至resources
目录,然后可以执行以下操作:
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
}
这篇关于如何在Scala中使用相对路径读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!