java 在 Playframework 中获取资源文件作为 InputStream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6888343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a resource file as an InputStream in Playframework
提问by bArmageddon
Play.classloader.getResourceAsStream(filepath);
filepath - relative to what? project root? playframework root? absolute path?
文件路径 - 相对于什么?项目根?游戏框架根?绝对路径?
Or maybe the usage Play.classloader.getResourceAsStream is wrong?
或者也许使用 Play.classloader.getResourceAsStream 是错误的?
回答by Eamonn O'Brien-Strain
In the Play Framework the "conf" directory is on the classpath, so you can put your file there and open it with getResourceAsStream.
在 Play Framework 中,“conf”目录位于类路径中,因此您可以将文件放在那里并使用 getResourceAsStream 打开它。
For example if you create a file "conf/foo.txt" you can open it using
例如,如果您创建一个文件“conf/foo.txt”,您可以使用
Play.classloader.getResourceAsStream("foo.txt");
回答by cdmckay
As an alternative to using the conf
dir (which should only be used for configuration-related files), you can use the public
dir and access it with:
作为使用conf
dir(应该仅用于与配置相关的文件)的替代方法,您可以使用public
dir 并通过以下方式访问它:
Play.classloader.getResourceAsStream("public/foo.txt")
Or in Scala with:
或者在 Scala 中使用:
Play.resourceAsStream("public/foo.txt")
回答by josephpconley
The accepted answer is deprecated in Play 2.5.x as global access to things like a classloader is slowly being phased out. The recommended way to handling this moving forward is to inject a play.api.Environment
then using its classLoader
to get the InputStream
, e.g.
接受的答案在 Play 2.5.x 中已弃用,因为对类加载器之类的全局访问正在慢慢被淘汰。处理这种前进的推荐方法是注入 aplay.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))
...
}
}
回答by Georgi Georgiev
Inject Environment
and then call environment.resourceAsStream("filename");
注入Environment
然后调用environment.resourceAsStream("filename");
Example:
例子:
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
}
}
Documentation: https://www.playframework.com/documentation/2.6.9/api/java/play/Application.html
文档:https: //www.playframework.com/documentation/2.6.9/api/java/play/Application.html
回答by Bozho
Relative to the classpath root. That is, your WEB-INF/classes
+ all the jars in WEB-INF/lib
相对于类路径根。也就是说,你的WEB-INF/classes
+ 所有的罐子WEB-INF/lib