遇java.io.FileNotFoundException报错,文件存在却无法识别求助
java.io.FileNotFoundException for Your APNs Auth Key File Let’s break down why you’re hitting this error even though the file exists, and walk through fixes step by step:
Common Causes & Solutions
1. Your JVM’s working directory isn’t what you expect
When you use a relative path like "AuthKey_7RHM5B8NS7.p8", Java looks for the file relative to the JVM’s current working directory—not the folder where your code file is stored.
To confirm this, add a quick debug line to print the working directory:
System.out.println("Current JVM working directory: " + System.getProperty("user.dir"));
Run your code and check the output. If your auth key file isn’t in that directory, that’s the root issue.
2. Test with an absolute path (quick sanity check)
As a temporary test, replace the relative path with the full absolute path to your file. For example:
new File("/Users/yourname/projects/yourapp/AuthKey_7RHM5B8NS7.p8")
If this works, you’ve confirmed the problem is with relative path resolution, not the file itself.
3. Load the file reliably (for Maven/Gradle projects)
The best practice for project resources is to place your auth key in the src/main/resources folder. Then use the class loader to load it—this works no matter where your JVM is launched from:
final ApnsClient apnsClient = new ApnsClientBuilder() .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST) .setSigningKey(ApnsSigningKey.loadFromPkcs8InputStream( getClass().getResourceAsStream("/AuthKey_7RHM5B8NS7.p8"), "GL87ZNESF6", "7RHM5B8NS7" )) .build();
4. Double-check permissions & case sensitivity
- On Linux/macOS, ensure the file has read permissions for the user running your app. Run
ls -l AuthKey_7RHM5B8NS7.p8in terminal—you should seerin the permissions string (e.g.,-rw-r--r--). - Filenames are case-sensitive on Unix-like systems. Make sure your code’s filename matches exactly (no typos like
authkey_7rhm5b8ns7.p8instead ofAuthKey_7RHM5B8NS7.p8).
5. Build the path dynamically (if the file stays in project root)
If you need to keep the file in your project root instead of resources, build the path using the project directory:
Path keyFilePath = Paths.get(System.getProperty("user.dir"), "AuthKey_7RHM5B8NS7.p8"); final ApnsClient apnsClient = new ApnsClientBuilder() .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST) .setSigningKey(ApnsSigningKey.loadFromPkcs8File(keyFilePath.toFile(), "GL87ZNESF6", "7RHM5B8NS7")) .build();
内容的提问来源于stack exchange,提问作者George

