2017-08-14 184 views
1

我嘗試從文件中將屬性加載到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而沒有解決這個問題。

回答

0

讓我們假設你有以下文件夾結構:

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

而且你LAMBDA處理程序:

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

ŧ帽子可能會工作...

+0

謝謝您的回答。我試着用和不用斜槓(「config.properties」和「/config.properties」)。沒有工作。 – greg

0

當你想加載一個屬性文件,你可以使用ResourceBundle加載屬性。

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

這不同於加載文件作爲InputStream,但這對我有效。

我有一個簡單的Hello-World Lambda,它從github上的屬性文件中讀取當前版本。

0

如果你在的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();