I have a CSV file. Where should I place it and how do I read the file?
4 Answers
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
.
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)
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
-
1doesn't simply
val iter = io.Source.fromFile("/public/myfile.csv").getLines
work? Oct 12, 2012 at 0:06 -
Using fromFile gave me
play.api.UnexpectedException: Unexpected exception [FileNotFoundException: /public/myfile.csv (No such file or directory)]
– samwizeOct 12, 2012 at 3:44
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