bAr*_*don 20 java playframework
Play.classloader.getResourceAsStream(filepath);
Run Code Online (Sandbox Code Playgroud)
filepath - 相对于什么?项目根?playframework root?绝对路径?
或者使用Play.classloader.getResourceAsStream是错误的?
Eam*_*ain 22
在Play Framework中,"conf"目录位于类路径中,因此您可以将文件放在那里并使用getResourceAsStream打开它.
例如,如果您创建文件"conf/foo.txt",则可以使用它来打开它
Play.classloader.getResourceAsStream("foo.txt");
Run Code Online (Sandbox Code Playgroud)
cdm*_*kay 10
作为使用confdir(仅应用于配置相关文件)的替代方法,您可以使用publicdir并使用以下命令访问它:
Play.classloader.getResourceAsStream("public/foo.txt")
Run Code Online (Sandbox Code Playgroud)
或者在Scala中:
Play.resourceAsStream("public/foo.txt")
Run Code Online (Sandbox Code Playgroud)
jos*_*ley 10
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))
...
}
}
Run Code Online (Sandbox Code Playgroud)
注入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
}
}
Run Code Online (Sandbox Code Playgroud)
文档:https : //www.playframework.com/documentation/2.8.0/api/java/play/Environment.html#resourceAsStream-java.lang.String-
| 归档时间: |
|
| 查看次数: |
13797 次 |
| 最近记录: |