- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Weird behavior with scala.io.Source
Sun, 2012-02-19, 10:24
Hello all,
I discovered something very strange with scala.io.Source, would like
to understand why it's behave that way.
First, let's see how mkString and getLines.mkString("\n") work with
Source.fromString:
scala> io.Source.fromString("a\nb\nc\nd").mkString
res4: String =
a
b
c
d
scala> io.Source.fromString("a\nb\nc\nd").getLines.mkString("\n")
res6: String =
a
b
c
d
*Perfect*, both have same result, which is exactly the string given in
input "a\nb\nc\nd".
And now let's see how fromFile.mkString is broken in my opinion:
First I create a file named "test.txt" with that exact content "a\nb\nc
\nd" ... where \n are real line return, and note there is NO line
return at end.
Then:
scala> io.Source.fromFile(new
java.io.File("test.txt")).getLines.mkString("\n")
res1: String =
a
b
c
d
*CORRECT* Same result as before, then:
scala> io.Source.fromFile(new java.io.File("test.txt")).mkString
res0: String =
"a
b
c
d
"
WTF? there is an added "\n" at the end of the string!
Why such behavior is there any reason, or it's just a bug?
Thanks for your help,
Alois Cochard
Never mind, after looking in the file in hexMode, I saw VIM add a
final \n to the file!
Thanks to multiHYP for pointing this out!
Cheers,
Alois Cochard
On Feb 19, 10:24 am, Alois Cochard wrote:
> Hello all,
>
> I discovered something very strange with scala.io.Source, would like
> to understand why it's behave that way.
>
> First, let's see how mkString and getLines.mkString("\n") work with
> Source.fromString:
>
> scala> io.Source.fromString("a\nb\nc\nd").mkString
> res4: String =
> a
> b
> c
> d
>
> scala> io.Source.fromString("a\nb\nc\nd").getLines.mkString("\n")
> res6: String =
> a
> b
> c
> d
>
> *Perfect*, both have same result, which is exactly the string given in
> input "a\nb\nc\nd".
>
> And now let's see how fromFile.mkString is broken in my opinion:
>
> First I create a file named "test.txt" with that exact content "a\nb\nc
> \nd" ... where \n are real line return, and note there is NO line
> return at end.
>
> Then:
>
> scala> io.Source.fromFile(new
> java.io.File("test.txt")).getLines.mkString("\n")
> res1: String =
> a
> b
> c
> d
>
> *CORRECT* Same result as before, then:
>
> scala> io.Source.fromFile(new java.io.File("test.txt")).mkString
> res0: String =
> "a
> b
> c
> d
> "
>
> WTF? there is an added "\n" at the end of the string!
>
> Why such behavior is there any reason, or it's just a bug?
>
> Thanks for your help,
>
> Alois Cochard