繁体   English   中英

读取项目目录以获取 java web 应用程序中的属性文件

[英]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。 另请注意将自动关闭InputStreamtry-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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM