AWS Lambda Java如何读取属性文件

问题描述:

我尝试从文件中将属性加载到Properties类中。我期望这个解决方案的工作:How to load property file from classpath in AWS lambda javaAWS Lambda Java如何读取属性文件

我有一个静态方法很少,我想用它作为配置持有人。里面有这条线

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

它总是返回null。我下载了Lambda正在使用的zip包,该文件位于根目录中。尽管如此,不工作。

任何人都有类似的问题?

编辑: 配置文件是在这里:

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

编辑: 我的 “临时” 的解决方法看起来像这样:

// 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."); 
     } 
    } 

在测试中,它从classpath中读取,在AWS LAMBDA部署后它使用文件系统的运行时。为了识别我使用的env变量文件:

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

但是我宁愿只是使用classpath而没有解决这个问题。

让我们假设你有以下文件夹结构:

project 
 
└───src 
 
│ └───main 
 
│  └───resources 
 
│   config.properties

而且你LAMBDA处理程序:

ClassLoader loader = Config.class.getClassLoader(); 
 
InputStream input = loader.getResourceAsStream("config.properties");

ŧ帽子可能会工作...

+0

谢谢您的回答。我试着用和不用斜杠(“config.properties”和“/config.properties”)。没有工作。 – greg

当你想加载一个属性文件,你可以使用ResourceBundle加载属性。

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

这不同于加载文件作为InputStream,但这对我有效。

我有一个简单的Hello-World Lambda,它从github上的属性文件中读取当前版本。

如果你在的src/main /资源包属性文件,试试这个:

protected static Properties readPropertiesFile() { 
    ClassLoader classLoader = Utils.class.getClassLoader(); 
    try { 
     InputStream is = classLoader.getResourceAsStream("PropertiesFile.properties"); 
     Properties prop = new Properties(); 
     prop.load(is); 
     return prop; 
    } catch (Exception e) { 
     return null; 
    } 
} 

你可以调用它是这样的:

Properties _dbProperties = Utils.readPropertiesFile();