在Playframework中将资源文件作为InputStream获取

Play.classloader.getResourceAsStream(filepath); 

filepath – 相对于什么? 项目根? playframework root? 绝对路径?

或者使用Play.classloader.getResourceAsStream是错误的?

在Play Framework中,“conf”目录位于类路径中,因此您可以将文件放在那里并使用getResourceAsStream打开它。

例如,如果您创建文件“conf / foo.txt”,则可以使用它来打开它

 Play.classloader.getResourceAsStream("foo.txt"); 

作为使用conf dir(仅应用于配置相关文件)的替代方法,您可以使用public目录并使用以下命令访问它:

  Play.classloader.getResourceAsStream("public/foo.txt") 

或者在Scala中:

  Play.resourceAsStream("public/foo.txt") 

在Play 2.5.x中不推荐使用已接受的答案,因为像类加载器这样的事物的全局访问正逐渐被逐步淘汰。 处理此前进的推荐方法是注入play.api.Environment然后使用其classLoader获取InputStream ,例如

 class Controller @Inject()(env: Environment, ...){ def readFile = Action { req => ... //if the path is bad, this will return null, so best to wrap in an Option val inputStream = Option(env.classLoader.getResourceAsStream(path)) ... } } 

注入Environment然后调用environment.resourceAsStream("filename");

例:

 import javax.inject.Inject; public class ExampleResource extends Controller{ private final Environment environment; @Inject public ExampleResource(Environment environment){ this.environment = environment; } public void readResourceAsStream() { InputStream resource = environment.resourceAsStream("filename"); // Do what you want with the stream here } } 

文档: https : //www.playframework.com/documentation/2.6.9/api/java/play/Application.html

相对于类路径根。 也就是说,你的WEB-INF/classes + WEB-INF/lib所有jar