[英]read project directory to get properties file in java web application
我正在嘗試准備在我的項目目錄src/test/resources/properties/api/
中顯示的屬性文件。 但是這種方式行不通,它給我的文件未找到異常。
請在下面找到我的代碼:
public Properties extractProperties() throws IOException {
InputStream configReader= null;
String env = getProperty("tuf.environment");
try {
configReader = new FileInputStream(new File("src/test/resources/properties/api/"+env+".properties")); // throwing exception
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
prop.load(configReader);
return prop;
}
我會按照以下方式進行。 請注意,如果找不到文件, extractProperties()
方法將返回一個空的Properties
object。 另請注意將自動關閉InputStream
的try-with-resources
語句。
public Properties extractProperties() throws IOException {
String env = getProperty("tuf.environment");
Properties prop = new Properties();
try (InputStream in = this.getClass().getResourceAsStream("/properties/api/" + env + ".properties")) {
prop.load(in);
} catch (Exception e) {
e.printStackTrace();
}
return prop;
}
從您的路徑來看,您使用的是 Maven 或 Gradle,因為它看起來像是它們使用的默認結構。 這意味着src/test/resources
指向類路徑的根,所以沒有src/test/resources
。 (這同樣適用於src/main/resources
。)。
所以如果你想加載它,你需要刪除加載的src/test/resources
部分。
接下來,如果這是從打包的應用程序運行,加載File
將不起作用,因為它不是File
。 File
需要是文件系統上的物理文件,而不是存檔內。
考慮到所有這些,您應該能夠使用以下內容加載屬性
public Properties extractProperties() throws IOException {
String env = getProperty("tuf.environment");
String resource = "/properties/api/"+env+".properties";
try (InputStream in = getClass().getResourceAsStream(resource)) {
prop.load(in);
return prop;
}
}
試試下面的東西
public Properties extractProperties() throws IOException {
Properties prop=new Properties();
String env = getProperty("tuf.environment");
String mappingFileName = "/properties/api/" + env+ ".properties";
Resource resource = resourceLoader.getResource("classpath:" + mappingFileName);
try (InputStream inputStream = resource.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream))) {
prop.load(bufferedInputStream);
} catch IOException ie) {
//handle exception
}
return prop;
}
可能env
不是您認為的那樣。 為什么不列出該目錄中的所有文件? 您可以使用https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/nio/file/Files.html#list(java.nio.file.Path)打印與相關目錄:
Path apiDir = Paths.get("src/test/resources/properties/api/");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.