0

I created a file with single line:

➜  ~ vi some_random_file_mkstring
➜  ~ wc -l < some_random_file_mkstring
       1

When I read the file using Source.fromFile and create a string using mkString it appends a newLine but if I do .getLines().mkString it doesn't append a newLine character.

scala> io.Source.fromFile("some_random_file_mkstring").mkString
res0: String =
"somerandomstring
"

scala> io.Source.fromFile("some_random_file_mkstring").mkString.contains("\n")
res1: Boolean = true

scala> io.Source.fromFile("some_random_file_mkstring").getLines().mkString.contains("\n")
res2: Boolean = false

Is this desired behavior? I am using scala 2.12.4

curious
  • 2,908
  • 15
  • 25

1 Answers1

1

vi adds a line feed character at the end of files, and wc accounts for this. If you do xxd some_random_file_mkstring my guess is you'll see a '0a' (\n) at the end.

So given that your file does actually contain that character, this seems like desired behavior to me. mkString just takes every character in the file, and getLines returns lines without the separator.

For more info about why this is the case, this other answer has some good context.

Joe K
  • 18,204
  • 2
  • 36
  • 58
  • Thanks, echo was also doing the same thing. I used `echo -n > some_file`. Didn't know about this in vi – curious Apr 04 '18 at 17:22