获取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\tomcat6.0.37\bin

  我获取的dir2 为    D:\Tocat\tomcat6.0.37\webapps\你的项目名\WEB-INF\classes\META-INF\config\filedir.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、总结

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

 

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

 

posted on 2015-08-03 21:17  WhyWin  阅读(7736)  评论(0编辑  收藏  举报

导航