Java读取properties文件内容

来源:互联网 发布:手机真假检测软件 编辑:程序博客网 时间:2024/06/04 19:51

java的properties文件需要放到classpath下面,这样程序才能读取到,有关classpath实际上就是java类或者库的存放 路径,在java工程中,properties放到class文件一块。在web应用中,最简单的方法是放到web应用的WEB-INF/classes 目录下即可,也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到classpath变量中,这样也也可 以读取到。在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF/classes其 实也是,java工程的class文件目录也是。

文件内容:

ip=127.0.0.1    port=8080

代码:

private String IP;//a.properties的ipprivate String port;//a.properties的portpublic String getIP() {return IP;}public void setIP(String iP) {IP = iP;}public String getPort() {return port;}public void setPort(String port) {this.port = port;}/**写ReadProperties方法 * @return */public void ReadProperties(){Properties p=new Properties();InputStream is;try {is=getClass().getResourceAsStream("/a.properties");p.load(is);Set KeyValue=p.keySet();for(Iterator i=KeyValue.iterator();i.hasNext();){String key=(String)i.next();if(key.equals("ip")){IP=(String) p.get(key);}else if(key.equals("port")){port=p.get(key).toString();}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//return "";System.out.println("从a.properties中获得信息:"+IP+port);}


 

0 0
原创粉丝点击