gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:18:41 25 4
gpt4 key购买 nike

我需要加载 key 文件才能在我的服务器上创建 GoogleCredential 实例。我使用

获取了 WEB-INF/resources 目录中资源的 URL
url = servletContext.getResource(RESOURCES_FOLDER + "/" + filePath);

返回:

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

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

使用

创建 文件
f = new File(url.getFile());

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

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

如何在 Web 服务器上下文中将 URL 转换为文件?或者有更简单的方法来创建GoogleCredential 实例

最佳答案

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

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

更新:

实际上,我也会查看您用于获取资源的 URL。每当您使用 .getResource 时,默认 URL 都会指向 /src/main/resources 目录。您传递到 .getResources 方法中的 url 应该是该点之后的任何文件夹结构。

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

   -src
-main
-resources
-googlecredentials.properties

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

如果我的文件夹结构是:

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

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

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

关于java - 在 Web 应用程序上下文中从 Uri 转换为文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com