java读取properties配置文件代码,properties配置文件,在java中一般使用pr
分享于 点击 29065 次 点评:137
java读取properties配置文件代码,properties配置文件,在java中一般使用pr
在java中一般使用properties文件做配置文件,其格式就是一个一个的键值对。
如下是peoperties文件示例:
# this a comment! this a comment tooDBuser=anonymousDBpassword=&8djsxDBlocation=bigone
java代码
import java.util.*;import java.io.*;class ReadProps { public static void main(String args[]) { ReadProps props = new ReadProps(); props.doit(); } public void doit() { try{ Properties p = new Properties(); p.load(new FileInputStream("user.props")); System.out.println("user = " + p.getProperty("DBuser")); System.out.println("password = " + p.getProperty("DBpassword")); System.out.println("location = " + p.getProperty("DBlocation")); p.list(System.out); } catch (Exception e) { System.out.println(e); } }}
Properties类是Hashtable的子类。我们可以通过get和put方法来读写其内容。 save方法可以保存修改后的内容。
import java.util.*;import java.io.*;class WriteProps { public static void main(String args[]) { WriteProps props = new WriteProps(); props.doit(); } public void doit() { try{ Properties p = new Properties(); p.load(new FileInputStream("user.props")); p.list(System.out); // new Property p.put("today", new Date().toString()); // modify a Property p.put("DBpassword","foo"); FileOutputStream out = new FileOutputStream("user.props"); p.save(out, "/* properties updated */"); } catch (Exception e) { System.out.println(e); } }}
您也可以把配置文件放到服务器端,然后通过load方法载入服务器端的配置文件,如下示例代码:
p.load((new URL(getCodeBase(), "user.props")).openStream());
当然也可以把配置文件放到资源文件中和项目一期打包,如下读取资源文件中的properties文件的示例:
URL url = ClassLoader.getSystemResource("/com/rgagnon/config/system.props");if (url != null) props.load(url.openStream());
用户点评