You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Play Framework 2.6+版本中读取资源文件?

在Play Framework 2.6+中正确读取conf/i18n目录下的文件

嘿,我明白你的困扰——之前的方案都是针对旧版本的,注入Environment后好像没起到预期效果,而且用System.getProperty("user.dir")这种方式在不同环境下很容易掉坑。咱们一步步来解决这个问题:

首先,别再用System.getProperty("user.dir")了!

这个方法获取的是当前JVM的工作目录,不是你的Play应用根目录,在容器部署、打包成jar运行时,这个路径完全不对。你已经注入了play.api.Environment,它才是获取应用路径的正确姿势。

正确使用Environment读取文件

1. 获取应用根目录下的conf/i18n目录(开发环境适用)

开发时,conf目录是在文件系统里的,你可以用env.rootPath来拿到应用的根路径,然后拼接出i18n目录的路径:

@Singleton
class Application @Inject() (
  configuration: play.api.Configuration,
  assets: AssetsFinder,
  env: play.api.Environment
) extends InjectedController {

  // 直接用env.rootPath构造i18n目录的File对象
  private val i18nDirectory = new File(env.rootPath, "conf/i18n")

  // 示例:列出i18n目录下的所有文件
  def getI18nFiles = Action {
    if (i18nDirectory.exists() && i18nDirectory.isDirectory) {
      val fileNames = i18nDirectory.listFiles().map(_.getName).mkString("\n")
      Ok(s"i18n目录下的文件:\n$fileNames")
    } else {
      NotFound("conf/i18n目录不存在,请检查路径是否正确")
    }
  }
}

2. 生产环境打包成jar后的处理

当你把应用打包成jar运行时,conf目录会被打包到jar内部,这时候用File对象是无法访问到里面的资源的,得用Environment提供的资源流方法来读取:

// 示例:读取jar内conf/i18n下的messages.en文件
def readI18nResource = Action {
  env.resourceAsStream("conf/i18n/messages.en") match {
    case Some(inputStream) =>
      // 读取流中的内容
      val content = scala.io.Source.fromInputStream(inputStream).mkString
      inputStream.close()
      Ok(content)
    case None =>
      NotFound("找不到指定的i18n资源文件")
  }
}

3. 兼容开发和生产环境的写法

你可以通过env.mode来判断当前运行环境,自动切换处理方式:

def handleI18nFiles = Action {
  if (env.mode == play.api.Mode.Dev) {
    // 开发环境用File操作
    val files = i18nDirectory.listFiles().map(_.getName)
    Ok(views.html.i18nList(files))
  } else {
    // 生产环境用资源流读取
    val resourceNames = List("messages.en", "messages.zh")
    val existingResources = resourceNames.filter(name => env.resource(s"conf/i18n/$name").isDefined)
    Ok(views.html.i18nList(existingResources))
  }
}

最后检查一下

  • 确认你注入的是play.api.Environment(如果是Java项目则是play.Environment,注意包名)
  • 开发时确保conf/i18n目录确实存在,路径拼写没有错误
  • 生产打包时,确认conf/i18n下的文件已经被正确打包到jar中(Play默认会打包conf目录下的所有文件)

内容的提问来源于stack exchange,提问作者kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:27:13