Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda Java how to read properties file

I try to load properties into Properties class from a file. I would expect this solution to work: How to load property file from classpath in AWS lambda java

I have a class with few static methods and I want to use it as a Config holder. Inside it there is this line

final InputStream inputStream = 
Config.class.getClass().getResourceAsStream("/application-main.properties");

and it always returns null. I downloaded the zip package that Lambda is using and the file is inside in root. Does not work nevertheless.

Anyone had similar issue?

EDIT: config file is here:

project
└───src
│   └───main
│      └───resources
│            application-main.properties

EDIT: My "temporary" workaround looks like that:

// LOAD PROPS FROM CLASSPATH...
try (InputStream is = Config.class.getResourceAsStream(fileName)) {
        PROPS.load(is);
    } catch (IOException|NullPointerException exc) {
        // ...OR FROM FILESYSTEM
        File file = new File(fileName);
        try (InputStream is = new FileInputStream(file)) {
            PROPS.load(is);
        } catch (IOException exc2) {
            throw new RuntimeException("Could not read properties file.");
        }
    }

During tests it reads from classpath, after deployment in AWS Lambda runtime it uses filesystem. To identify the file I used env variable:

fileName = System.getenv("LAMBDA_TASK_ROOT")  + "/application-main.properties";

But I would rather just use classpath without working this around.

like image 953
greg Avatar asked Mar 09 '23 08:03

greg


2 Answers

Assuming src/main/resources/config.properties

File file = new File(classLoader.getResource("resources/config.properties").getFile());
FileInputStream fileInput = new FileInputStream(file);
prop.load(fileInput);
like image 162
user3466099 Avatar answered Mar 10 '23 21:03

user3466099


As you want to load a properties file you can use the ResourceBundle to load the properties.

String version = ResourceBundle.getBundle("application-main").getString("version");

It's not the same as loading file as an InputStream, but this worked for me.

I have a simple Hello-World Lambda which reads the current version from a properties file on github.

like image 34
Udo Held Avatar answered Mar 10 '23 22:03

Udo Held