0

I have a file which contains certain string like -

Apple
Google
Microsoft

I am reading in this file as

val lines = scala.io.Source.fromFile(filePath).mkString.replace("\n", ",")

Which results in a comma separated list of string. However what I really want is "Apple","Google","Microsoft"

If I add double quotes in the string replace while reading in the file I while have to take care of the first and last double quotes which won't be ideal. How should I go about this?

2 Answers 2

3

One option is to load each line into an Iterator and then let mkString apply the commas and quote marks.

io.Source
  .fromFile(filePath)
  .getLines()
  .mkString("\"","\",\"","\"")
//res0: String = "Apple","Google","Microsoft"
Sign up to request clarification or add additional context in comments.

2 Comments

The output for me is now looking like - "A","p","p","l","e".......
Are you using .getLines (and only .getLines) to read from the file?
1

Similar to jwvh's answer but with Using for resource management

import scala.util.Using
import scala.io.Source

Using.resource(Source.fromFile(filePath)) { file =>
  file.getLines.map(line => s""""$line"""").mkString(",")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.