Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

eclipse - Scala Eclipse项目-无法从资源目录读取文本文件(Scala Eclipse project - unable to read text file from resources directory)

I'm trying to read text file located in resources directory using Scala version 2.12.3.

(我正在尝试使用2.12.3版的Scala读取位于资源目??录中的文本文件。)

However I'm getting file not found error.

(但是我得到文件找不到错误。)

my project in eclipse

(我的日食项目)

在此处输入图片说明

my scala code:

(我的scala代码:)

package main.scala
import scala.io.Source
import scala.io.Codec
object Application {
  def main(args: Array[String]) {
    try {
      val source = Source.fromFile("sample.txt")(Codec.UTF8)
      for (line <- source.getLines) {
        println(line.toUpperCase)
      }
      source.close
    } catch {
      case e: Throwable => e.printStackTrace()
    }
  }
}

I also tried using

(我也尝试使用)

val source = Source.fromFile("sample.txt")(Codec.UTF8)

but got the same error.

(但是出现了同样的错误。)

  ask by SoleQuantum translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to read file from src/main/resources directory you should use Source.fromResource method, so try this:

(如果要从src/main/resources目录读取文件,则应使用Source.fromResource方法,因此请尝试以下操作:)

Source.fromResource("sample.txt")(Codec.UTF8)

Update

(更新资料)

In your case you have to use either Source.fromFile("src/main/resources/sample.txt") or Source.fromFile("sample.txt") if you put your file in root project directory

(如果您将文件放在根项目目录中,则必须使用Source.fromFile("src/main/resources/sample.txt")Source.fromFile("sample.txt"))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...