1

I have input file i would like to read a scala stream and then modify each record and then output the file.

My input is as follows -

Name,id,phone-number
abc,1,234567
dcf,2,345334

I want to change the above input as follows -

Name,id,phone-number
    testabc,test1,test234567
    testdcf,test2,test345334

I am trying to read a file as scala stream as follows:

val inputList = Source.fromFile("/test.csv")("ISO-8859-1").getLines

after the above step i get Iterator[String]

val newList = inputList.map{line => 
              line.split(',').map{s =>
                "test" + s
              }.mkString (",")
          }.toList

but the new list is empty. I am not sure if i can define an empty list and empty array and then append the modified record to the list. Any suggestions?

9
  • Are you actually managing to read the file? Commented Feb 14, 2017 at 16:32
  • i am able to read the file. but i am stuck with modifying the data.the following code - val newList = inputList.map{line => line.split(',').map{s => println("test" + s) } } Commented Feb 14, 2017 at 16:34
  • missing return in the first map? Commented Feb 14, 2017 at 16:34
  • @Dimitri Why does he need return? Commented Feb 14, 2017 at 16:34
  • 1
    yes, thats correct. this was the problem. as soon as removed the inputlist.println() from the code. It worked. Thanks! I should change the iterator to list. Commented Feb 14, 2017 at 16:45

2 Answers 2

1

You might want to transform the iterator into a stream

val l = Source.fromFile("test.csv")
    .getLines()
    .toStream
    .tail
    .map { row =>
      row.split(',')
        .map { col =>
         s"test$col"
        }.mkString (",")
     }

  l.foreach(println)

testabc,test1,test234567

testdcf,test2,test345334

Sign up to request clarification or add additional context in comments.

Comments

1

Here's a similar approach that returns a List[Array[String]]. You can use mkString, toString, or similar if you want a String returned.

scala> scala.io.Source.fromFile("data.txt")
  .getLines.drop(1)
  .map(l => l.split(",").map(x => "test" + x)).toList

res3: List[Array[String]] = List(
  Array(testabc, test1, test234567), 
  Array(testdcf, test2, test345334)
)

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.