3

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

2

4 Answers 4

1

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.

1

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)

0

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
2
  • 1
    doesn'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)]
    – samwize
    Oct 12, 2012 at 3:44
0

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.