samwize
samwize

Reputation: 27383

How to read a file in Scala with Play! 2.0?

I have a CSV file. Where should I place it and how do I read the file?

Upvotes: 3

Views: 3347

Answers (4)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102458

This is how I got it working here:

import java.io._

def index = Action {

    //Ok(views.html.index())

    Ok.sendFile(new java.io.File("../spark-backend/csv/UsersGroupedByRegistrationMonthYear.csv"))

}

There's some good documentation here: https://www.playframework.com/documentation/2.0.1/ScalaStream

Upvotes: 0

Jockbert
Jockbert

Reputation: 102

Using io.Source.fromFile("/public/myfile.csv") also works for files outside of the classpath.

Caveat: For a relative path to your public folder you should start with "public/..." or "./public/..." instead of using the absolute path "/public/...".

(n.b. I didn't have the reputation to directly reply to comment by Luigi Plinge)

Upvotes: 1

samwize
samwize

Reputation: 27383

I ended up putting the file under /public.

Then Read using

import scala.io.Source

val is = Application.getClass().getResourceAsStream("/public/myfile.csv")    
val src = Source.fromInputStream(is)
val iter = src.getLines

Upvotes: 0

Kim Stebel
Kim Stebel

Reputation: 42045

You can use this scala wrapper for opencsv. You can put your file on the classpath and then use getClass.getResourceAsStream("file.csv") to get an InputStream.

Upvotes: 1

Related Questions