How to read a file in AWS Lambda Function written in Java ?

前端 未结 4 538
庸人自扰
庸人自扰 2021-02-04 15:24

I have written an AWS Lambda Handler as below :

package com.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.r         


        
4条回答
  •  耶瑟儿~
    2021-02-04 16:05

    This is how I did it, let's say this is how your project structure looks like -

    And you want to read the file config.properties which is inside the project-dir/resources directory.

    The code for reading the content of the file would be -

    InputStream input = null;
    try {
        Path path = Paths.get(PropertyUtility.class.getResource("/").toURI());
    
        // The path for config file in Lambda Instance -
        String resourceLoc = path + "/resources/config.properties";
    
        input = new FileInputStream(resourceLoc);
    } catch(Exception e) {
        // Do whatever
    }
    

    If you are following this project structure and using this code, then it will work in AWS Lambda.

    PropertyUtility is just a utility class that I have created to read the contents of the config file. The PropertyUtility class looks like this -

    As you can see in the above code, the path of the config file is different in the local system and in Lambda Instance.

    In your local machine, PropertyUtility.class.getResource("/") points to bin, that is why you have to do path.getParent(), to point it to the project-directory which is HelloLambda in this example.

    For the Lambda Instance, PropertyUtility.class.getResource("/") points directly to the project-directory.

提交回复
热议问题