当前位置: 移动技术网 > IT编程>开发语言>Java > java web开发中获取tomcat上properties文件内容的方法

java web开发中获取tomcat上properties文件内容的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

在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、总结

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网