属性文件不会针对相对路径进行加载和更新,但对于绝对路径则可以正常工作

时间:2019-03-26 06:01:12

标签: java

我正在尝试从src/main/resources文件夹访问属性文件,但是当我尝试使用相对路径加载该文件时,该文件没有得到更新。但这绝对可行。

我需要动态Web项目才能在所有平台上工作。

public static void loadUsers() {

  try(
    FileInputStream in = new FileInputStream("C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties")) {
    // write code to load all the users from the property file
    // FileInputStream in = new FileInputStream("classpath:users.properties");

    users.load(in);
    System.out.println(users);
    in.close();

  }
  catch(Exception e){
    e.printStackTrace();
  }

2 个答案:

答案 0 :(得分:0)

首先,您正在使用Spring,至少那是底部的标签所说的。其次,C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties是类路径的根。不用加载File,而使用Spring resource abstraction

由于这是类路径的一部分,因此您可以简单地使用ClassPathResource获得适当的InputStream。无论您处于哪种环境,它都将起作用。

try( InputStream in = new ClassPathResource("users.properties").getInputStream()) {
    //write code to load all the users from the property file
    //FileInputStream in = new FileInputStream("classpath:users.properties");
    users.load(in);
    System.out.println(users);
} catch(Exception e){
    e.printStackTrace();
}

注意::您已经在尝试使用资源,因此不需要关闭已经为您处理的InputStream

更改应用程序内部的内容根本行不通,因为这意味着您可以更改jar中的资源(读取类),这会带来很大的安全风险!如果您希望更改某些内容,则必须将其设置为类路径之外的文件,并直接在文件系统上。

答案 1 :(得分:0)

尝试以下代码

import java.io.FileInputStream; 导入java.io.IOException;

公共类LoadUsers {

公共静态void main(String [] args)引发IOException {

GET /_search
{
  "size": 0,
  "query": {
    "match": {
      "type": "Certain Type"
    }
  },
  "aggs": {
    "avg time": {
      "nested": {
        "path": "lineItems.events"
      },
      "aggs": {
        "avg time": {
          "avg": {
            "script": {
              "lang": "painless",
              "source": """
          long timeDiff = 0; 
          long fromTime = 0; 
          long toTime = 0; 
          if(doc['lineItems.events.name.keyword'] == "CREATED"){
            fromTime = doc['lineItems.events.timeValue'].value.getMillis();
          }
          else if(doc['lineItems.events.name.keyword'] == "ENDED"){
            toTime = doc['lineItems.events.timeValue'].value.getMillis();
          }
          timeDiff = toTime-fromTime;
          return (timeDiff)
          """
            }
          }
        }
      }
    }
  }
}

}

相关问题