有时候,我们在编写java程序的时候,都是把一些可配置的新的写到配置文件里,但是不能跟项目一起打包,因为配置文件可能会需要经常修改,所以最好能在同级目录。
项目结构如下

可以看到,app.properties在同级目录下,打包为可执行jar过后,jar包里面没有app.properties文件,放到了外面,然后就可以轻松修改了。
工具类
/*** 用完美的单例模式获取properties的数据,加载为map* @author forever**/public class PropertiesUtil {//值可变,引用不可变private static final Properties PROPERTIES =new Properties();static{initProperties();}/*** @param key* @param defaultValue* @return*/public static String get(String key,String defaultValue){if(PROPERTIES.isEmpty()) {throw new UnsupportedOperationException("配置未加载");}String value =PROPERTIES.getProperty(key, defaultValue);return value;}/*** 获取默认配置的值,这个值可以动态修改* @param key* @return*/public static String get(String key){return get(key, "");}private static void initProperties(){InputStream is =null;try {//获取当前目录String property = System.getProperty("user.dir");//默认是linux osString fileName = "/app.properties";//判断是否是windows osif(System.getProperty ("os.name").contains("Windows")) {fileName = "\\app.properties";}// 读取当前目录下conf配置文件File file = new File(property+fileName);PROPERTIES.clear();is = new FileInputStream(file);PROPERTIES.load(new InputStreamReader(in,"UTF-8"));}catch (IOException e) {e.printStackTrace();}finally {if(is!=null) {try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public static void main(String[] args) {System.out.println(PropertiesUtil.get("name"));}}
