【问题标题】:How to read a text file using Relative path in scala如何在scala中使用相对路径读取文本文件
【发布时间】:2026-01-20 17:40:01
【问题描述】:

我有一个用 scala 编写的简单 mvn 项目。我想访问一个文本文件并阅读其内容。代码工作正常,但唯一的问题是我在读取文本文件时给出了绝对路径。以下是我的项目的目录结构。

如何使用相对路径来读取该文件? (我是否必须将 movies.txt 文件移动到资源目录中,如果仍然如此,我将如何读取该文件?)

任何见解将不胜感激。谢谢你

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

在其中 Simulate 是包对象的 myobject.scala 中,我使用绝对路径访问 movies.txt 文件。

import scala.io.Source
Source
    .fromFile("/home/eshan/projecs/myproject/movies.txt")
    .getLines
    .foreach { line =>
    count+=1
      // custom code            
}

【问题讨论】:

  • os-lib 是最好的现代解决方案,有关详细信息,请参阅我的答案。

标签: scala maven


【解决方案1】:

将您的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            
}

【讨论】:

  • 您好,我想这可行。我收到一个不相关的错误,即在 target/myproject/lib 中找不到 movies.txt 文件。一旦我修复它,我相信你的解决方案会奏效。感谢您的快速回复。
  • 我不得不将 .txt 更改为 .conf。 (解决不相关的问题)。然后,您的解决方案适用于 movies.conf,并将“import java.io.File”添加到我的 scala 代码中。谢谢
  • 当我尝试使用您的方法时出现错误reference to getClass is ambiguous; it is both defined in class Object and imported subsequently by import sparkSession.implicits._,但不明白为什么?有什么想法吗?
  • @Andrey... 只需使用 this.getClass 而不是 getClass
【解决方案2】:

你可以更简洁地使用:

Source.fromResource("movies.txt") 

它将查找相对于资源文件夹的路径。

【讨论】:

    【解决方案3】:

    os-lib 是使用 Scala 读取文件的最佳方式。

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

    os-lib 也是 supports relative paths,但这里不应该需要这些。

    该库可以轻松读取文件、构建路径和其他文件系统操作,请参阅here 了解更多详细信息。

    【讨论】: