This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Weird behavior with scala.io.Source

1 reply
alois.cochard
Joined: 2010-03-19,
User offline. Last seen 34 weeks 2 hours ago.

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

alois.cochard
Joined: 2010-03-19,
User offline. Last seen 34 weeks 2 hours ago.
Re: Weird behavior with scala.io.Source

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

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland