问题
Using Java 8, I have an AWS lambda function that has a flat file in the src/main/resources
folder. When running on AWS, I'm having no issues. But when I run locally, my app can't find the file.
Here is what my code looks like:
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource( "./resources/forms/myform.pdf" );
This works fine for loading it when it runs as an AWS lambda, but does not work locally. When running locally, the url
variable is null. When I run the code on AWS, the ClassLoader is java.net.URLClassLoader
while locally it is sun.misc.Launcher$AppClassLoader
. I'm not sure if this matters.
Here is my file structure if it helps:
I'm using my ControllerTest
class. I'm not using the LambdaFunctionHandlerTest
that was created by default by AWS. Here is all that my ControllerTest
does:
public class ControllerTest {
public static void main( String[] args ) {
MyController controller = new MyController();
controller.create();
}
}
Any ideas how I can get this to work locally and on AWS? It's a maven project in Eclipse and I'm thinking the way I'm executing my controller in my test function is incorrect. Does the run configuration in eclipse need to be altered from the defaults?
Update: Changing my path to forms/myform.pdf
fixed the issue running locally. However, it now fails to find the file when running as an AWS lambda function. Here is the folder structure that is created in AWS:
回答1:
You may check the Maven Standard Directory Layout here: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
All your test classes along with test resources will be compiled and placed inside target/test-classes directory. In your case getClassLoader().getResource will return the path to target/test-classes directory where forms/myform.pdf is to be stored.
By default, the test class will find resources from your test-classes directory. If they are not found in the test-classes directory, the classes folder will be searched.
来源:https://stackoverflow.com/questions/59252738/unable-to-load-file-from-resources-folder-when-running-app-locally