Reading Files from public folder in play framework in production
Use Source.fromResource instead of Source.fromFile if you are using scala 2.12.
Example:
If you put the file in public folder, don't use the leading slash.
Source.fromResource(“public/files/abc.txt”)
If you put the file in conf folder, don't include conf in the path.
Source.fromResource(“files/abc.txt”) // conf/files/abc.txt
If you are using scala < 2.12, you can fall back to Java. There are 2 ways.
Relative path(no leading slash)
scala.io.Source.fromInputStream(getClass.getClassLoader.getResourceAsStream(“public/test.txt”))
Absolute path (leading slash required)
scala.io.Source.fromInputStream(getClass.getResourceAsStream(“/public/test.txt”))
I guess you also have to exclude "conf" in the path if you put the file in conf folder.
Lastly, you can learn how Java's resource loading works in this blog.
You can use this method:
Play.application().getFile("/public/foobar.baz");
Method Doc:
Get a file relative to the application root path.
Have you tried out this Play Documentation https://www.playframework.com/documentation/2.5.x/AssetsOverview ? This is Ok with Play 2.4 and even with 2.3 also, I have tried out.
In there you can find this, you can simply do this in your conf/routes file.
GET /assets/*file controllers.Assets.at(path="/public", file)
file -> refers to the file name. Ex: myFile.json
To make this work in production mode you have to do some little more work. As explained in this answer, add these lines into your /build.sbt file.
import com.typesafe.sbt.packager.MappingsHelper._
mappings in Universal ++= directory(baseDirectory.value / "public")
That would include your 'public' directory inside the dist file (You can include any directory like that way). Then your application would work in the production environment.