user2492364
user2492364

Reputation: 6693

scala read file,and each line save to a variable?

scalaresult.txt

0~250::250~500::500~750::750~1000::1000~1250
481::827::750::256::1000 

scala code

 val filename = "/home/user/scalaresult.txt"
 for ( (line,index) <- Source.fromFile(filename).getLines().zipWithIndex){ 
  println(line)
  println(index)
 }

 //val step_x = "0~250::250~500::500~750::750~1000::1000~1250"
 //val step_y = "481::827::750::256::1000"
Seq("java", "-jar", "/home/user/birt2.jar" , step_x , step_y , "BarChart").lines

I have a file: scalaresult.txt

I need to save first line (index(0)) to step_x and the second line (index(1)) to step_y

How to do this ? Please guide me Thank you.

Upvotes: 0

Views: 1653

Answers (2)

Arne Claassen
Arne Claassen

Reputation: 14404

If all you are trying to do it take the two lines from the file and inserting them into the sequence, the indexer on the list will do the trick. Mind you, it's an O(n) operation on list, so if there were a lot of lines, it wouldn't be the best approach.

val filename = "/home/user/scalaresult.txt"
val lines = Source.fromFile(filename).getLines()
val seq = Seq("java", "-jar", "/home/user/birt2.jar" , lines(0) , lines(1), "BarChart")

Upvotes: 0

eliasah
eliasah

Reputation: 40370

This is not the optimal solution, but you can try the following: (I'm not a scala expert yet! :P)

scala> val it = Source.fromFile(filename).getLines().toList
it: List[String] = List(0~250::250~500::500~750::750~1000::1000~1250, "481::827::750::256::1000 ")

scala> it(1)
res7: String = "481::827::750::256::1000 "

scala> it(0)
res8: String = 0~250::250~500::500~750::750~1000::1000~1250

Upvotes: 4

Related Questions