Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple file read with Scala does not work

Tags:

scala

Using Scala 2.10.2------------

I am a Java engineer, and started to learn Scala from yesterday, but I got stuck now, this simply code does not work for me, but when I use java to write it, it works fine:

    package lesson4

    import scala.io.Source
    import scala.reflect.io.File


    object Test {
        def main(args: Array[String]): Unit = {
        var filePath = Source.getClass().getResource("/lesson4/test.txt")
        var file = Source.fromFile(filePath.getFile())
        var lines = file.getLines
        lines.foreach(println)
  }
}

The file is in the right path: path But the code just does not work:

Exception in thread "main" java.io.FileNotFoundException: /Users/wenjiezhang/Desktop/source_files/git_hub%20workspace/Learning%20Scala/ScalaLearning/bin/lesson4/test.txt (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at scala.io.Source$.fromFile(Source.scala:90)
    at scala.io.Source$.fromFile(Source.scala:75)
    at scala.io.Source$.fromFile(Source.scala:53)
    at lesson4.Test$.main(Test.scala:20)
    at lesson4.Test.main(Test.scala)
like image 237
Jack Zhang Avatar asked Nov 24 '25 03:11

Jack Zhang


1 Answers

As you can see from the error log, the path you're providing is being converted to a URL (for example SPACE becomes %20). You should use the fromURL method Source.fromURL(Source.getClass().getResource("/lesson4/test.txt"))

scala.io.Source docs

like image 189
BahmanM Avatar answered Nov 26 '25 17:11

BahmanM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!