代码之家  ›  专栏  ›  技术社区  ›  special0ne

在web应用程序上下文中从Uri转换为文件路径

  •  0
  • special0ne  · 技术社区  · 11 年前

    我需要加载密钥文件来创建 GoogleCredential 我的服务器上的实例。 我得到了我的 WEB-INF/resources 目录使用

    url = servletContext.getResource(RESOURCES_FOLDER + "/" + filePath);
    

    其返回:

    "jndi:/localhost/<MY_APP>/WEB-INF/resources/<MY_FILE>"
    

    问题是 GoogleCredential.setServiceAccountPrivateKeyFromP12File 需要File对象作为参数。

    创建 File 使用

    f = new File(url.getFile());
    

    正在创建f,但路径错误。

    f.getAbsolutePath() = D:\localhost\<MY_APP>\WEB-INF\resources\secrets.p12
    

    如何在web服务器上下文中将URL转换为文件?还是有一种更简单的方法来创建 谷歌凭据 例子

    1 回复  |  直到 11 年前
        1
  •  1
  •   ninnemannk    11 年前

    试试这个-使用 this.getClass() 而不是servletContext:

    new java.io.File(this.getClass().getResource(RESOURCES_FOLDER + "/" + filePath).toURI());
    

    更新:

    事实上,我会看看你用来获取资源的URL。任何时候您都可以使用 .getResource ,默认url指向 /src/main/resources 目录传递到的url .getResources 方法应该是从此点起的任何文件夹结构。

    例如,如果我的文件夹结构是:

       -src
          -main
            -resources
               -googlecredentials.properties
    

    你需要传递的是: this.getClass().getResource("googlecredentials.properties");

    如果我的文件夹结构是:

       -src
          -main
            -resources
               -google
                  -googlecredentials.properties
    

    我需要传递: this.getClass().getResource("google/googlecredentials.properties");

    您永远不想在资源url前面加上 / 。这意味着您正在从硬盘驱动器的根目录(绝对路径)进行查看。您需要资源的相对路径。