zoukankan      html  css  js  c++  java
  • 获取tomcat上properties文件的内容——方便文件存储位置的修改,解耦和

      在java web开发的时候经常会用到读取读取或存放文件,这个文件的默认路径在哪里呢?写死在程序里面显然是可以的,但这样子不利于位于,假如有一天项目从window移植到linux,或者保存文件的路径变了,就需要去源代码中查找,进行替换,这样子不仅效率低,而且程序的耦合度也会过高,这里我用了一个properties文件用于存放文件的保存路径,需要保存或者读取都来自己properties所保存的路径。

    1、我存放的propeities文件路径

      因为linux和window上面的分盘是不一样的,所以我把保存文件路径的properties文件放在项目中,所以可以通过获取tomcat所以路径来获取该文件

    2、properties文件内容

      这里文件路径我使用了 / ,可以兼容linux系统和window,假如在程序中文件的分隔符建议使用File.separator作为分隔符,以兼容不同的操作系统。

    filePath=E:/file

    3、获取文件所在的路径

    String dir = System.getProperty("user.dir");  //获得tomcat所在的工作路径  
            System.out.println(dir);
            
            //获取到存储了文件存储位置的filedir.properties 文件路径
            String dir2 = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "NGBOSSmonitor" +File.separator + "WEB-INF"
                          + File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + "filedir.properties";

      dir 获取到的是  :D:Tocat omcat6.0.37in

      我获取的dir2 为    D:Tocat omcat6.0.37webapps你的项目名WEB-INFclassesMETA-INFconfigfiledir.properties

    4、通过properties文件,获取到里面的filePath的值,即获得 E:/file

    /**
         * 获取filePath路径【properities文件】中key对应的值,
         * @param filePath properities文件路径【包含properities文件】
         * @param key 要查找的key值
         * @return key对应的value
         */
         public  String GetValueByKey(String filePath, String key) {
                     Properties pps = new Properties();
                     try {
                          InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
                          pps.load(in);
                         String value = pps.getProperty(key);
                         //System.out.println(key + " = " + value);
                         in.close();
                         return value;
                         
                     }catch (IOException e) {
                         e.printStackTrace();
                         return null;
                     }
                 }

      到达这里,已经完整得获得了filedir.properties 里面得 filePath的值。

    5、总结

      开发过程中,使程序解耦合很重要,耦合程度越低,我们开发修改越容易。

      致谢:感谢您的耐心阅读!

  • 相关阅读:
    bootstrap 的页码显示问题-------------德州
    大神的---解决tomcat内存溢出问题----tomcat报错:This is very likely to create a memory leak问题解决
    如何设置tomcat,直接通过IP 访问
    如何把MyEclipse中的web项目导入到Eclipse中运行
    易捷框架之EChart 的使用
    打包jar文件并自动运行
    『PLSQL』在oracle表中怎样创建自增长字段?
    解决MySql 数据库 提示:1045 access denied for user 'root'@'localhost' using password yes
    Oracle 与 MySQL 批量添加
    SPR, subpixel rendering
  • 原文地址:https://www.cnblogs.com/0201zcr/p/4700418.html
Copyright © 2011-2022 走看看