个人随笔
目录
工具类:Java从项目可执行jar同级目录读取配置文件工具类
2020-09-11 23:02:05

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

项目结构如下

可以看到,app.properties在同级目录下,打包为可执行jar过后,jar包里面没有app.properties文件,放到了外面,然后就可以轻松修改了。

工具类

  1. /**
  2. * 用完美的单例模式获取properties的数据,加载为map
  3. * @author forever
  4. *
  5. */
  6. public class PropertiesUtil {
  7. //值可变,引用不可变
  8. private static final Properties PROPERTIES =new Properties();
  9. static{
  10. initProperties();
  11. }
  12. /**
  13. * @param key
  14. * @param defaultValue
  15. * @return
  16. */
  17. public static String get(String key,String defaultValue){
  18. if(PROPERTIES.isEmpty()) {
  19. throw new UnsupportedOperationException("配置未加载");
  20. }
  21. String value =PROPERTIES.getProperty(key, defaultValue);
  22. return value;
  23. }
  24. /**
  25. * 获取默认配置的值,这个值可以动态修改
  26. * @param key
  27. * @return
  28. */
  29. public static String get(String key){
  30. return get(key, "");
  31. }
  32. private static void initProperties(){
  33. InputStream is =null;
  34. try {
  35. //获取当前目录
  36. String property = System.getProperty("user.dir");
  37. //默认是linux os
  38. String fileName = "/app.properties";
  39. //判断是否是windows os
  40. if(System.getProperty ("os.name").contains("Windows")) {
  41. fileName = "\\app.properties";
  42. }
  43. // 读取当前目录下conf配置文件
  44. File file = new File(property+fileName);
  45. PROPERTIES.clear();
  46. is = new FileInputStream(file);
  47. PROPERTIES.load(new InputStreamReader(in,"UTF-8"));
  48. }catch (IOException e) {
  49. e.printStackTrace();
  50. }finally {
  51. if(is!=null) {
  52. try {
  53. is.close();
  54. } catch (IOException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }
  61. public static void main(String[] args) {
  62. System.out.println(PropertiesUtil.get("name"));
  63. }
  64. }
 1090

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2