Java 中我们往往通过定义常量来使用一些值,方便我们进行修改配置,如:

public classConstant {
  public static final String IMG_ORI_PATH = “ori/”;
  public static final String IMG_THUMB_PATH = “thumb/”;
  ……
}

这样我们在其他类中可以直接使用 Constant.IMG_ORI_PATH 来代替 “ori/” ,使用 Constant.IMG_THUMB_PATH 来代替 “thumb/”,等等。一旦这些路径发生改变,只需要修改 Constant 类,其他类不受影响,相信绝大多数开发人员对这一点很熟悉。然而,如果现在项目已经上线,还需要重新编译该类为.class 文件,相对来说时间成本比较大,而通过java.util.ResourceBundle java.util.Properties 两个类,我们可以大大减小这一时间成本。

ResourceBundle 通常用于针对不同的语言,即国际化来使用,只能针对.properties 文件,当然在这里我们不讨论国际化,只是用它来实现 Properties 的功能。如果程序中的属性文件只是一些配置,并不是针对多国语言,那么也可以使用 Properties ,该类可以针对 .properties .xml.txt 等各种类型的文件。

 

1. ResourceBundle

在项目的src/main/resources 目录下,创建一个自定义的 systemconfig.properties 文件。.properties 文件中的内容为 key-value 型,我们可以在其中添加如下值:

img.ori.path=ori/

img.thumb.path=thumb/

之后使用 ResourceBundle 来取值:

ResouceBundle resourceBundle = ResourceBundle.getBundle(“systemconfig”);
String oriPath = resourceBundle.getString(“img.ori.path”);
String thumbPath = resourceBundle.getString(“img.thumb.path”);

 

2. Properties

同样,在项目的src/main/resources 目录下,创建一个自定义的 systemconfig.txt文件,文件内容与上面的systemconfig.properties 相同,之后使用 Properties 来取值:

Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource(“systemconfig.txt”).getPath());
properties.load(fileInputStream);
String oriPath = properties.getProperty(“img.ori.path”);
String thumbPath = properties.getProperty(“img.thumb.path”);

当然,这里的systemconfig.txt 可以放在系统中的任何位置,只要在 new FileInputStream() 中明确文件路径即可。

 

通过以上两种方法,在路径发生变化时,我们只需要修改配置文件,无需重新编译.class 文件,节约的时间可以喝杯咖啡啦。