【问题标题】:Getting java.io.FileNotFoundException: FileName (No such file or directory)获取 java.io.FileNotFoundException: FileName (没有这样的文件或目录)
【发布时间】:2019-10-24 00:30:26
【问题描述】:

我收到错误“java.io.FileNotFoundException:AuthKey_7RHM5B8NS7.p8(没有这样的文件或目录)”,该文件显然在我的目录中,并且我正在使用该文件的相对路径。这是我的项目目录。

项目目录图片

final ApnsClient apnsClient = new ApnsClientBuilder()
    .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
    .setSigningKey(ApnsSigningKey.loadFromPkcs8File(new File("AuthKey_7RHM5B8NS7.p8"),
            "GL87ZNESF6", "7RHM5B8NS7"))
    .build();

【问题讨论】:

  • 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。
  • 使用:文件 f = new File(getClass().getClassLoader().getResource("filename").getFile());

标签: java maven servlets intellij-idea filenotfoundexception


【解决方案1】:

当您尝试从资源文件夹中获取文件时,您需要为其指定路径。

File file = new File(getClass().getResource("/AuthKey_7RHM5B8NS7.p8").getFile());

或获取网址

URL res = getClass().getClassLoader().getResource("AuthKey_7RHM5B8NS7.p8");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

【讨论】:

    【解决方案2】:

    您不应使用ApnsSigningKey.loadFromPkcs8File 方法,而应使用loadFromInputStream 方法。

    原因是您正在使用 资源 - 如果您从代码中构建 JAR 文件,就像通常所做的那样,您的资源将在 JAR 文件中,您将无法获取指向它的File 对象。

    代码:

    InputStream in = getClass().getResourceAsStream("/AuthKey_7RHM5B8NS7.p8");
    
    final ApnsClient apnsClient = new ApnsClientBuilder()
        .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
        .setSigningKey(ApnsSigningKey.loadFromInputStream(in, "GL87ZNESF6", "7RHM5B8NS7"))
        .build();
    
    in.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      相关资源
      最近更新 更多