搜课云网 > 上海内威培训 > 资讯总汇 > Properties类应用详解

Properties类应用详解

机构:上海内威培训 时间:2016-01-25 08:46:13 点击:609

  1、获取JVM的系统属性

  import java.util.Properties;

  public class ReadJVM {

  public static void main(String[] args) {

  Properties pps = System.getProperties();

  pps.list(System.out);

  }

  }

  2、随便新建一个配置文件(Test.properties)

  name=JJ

  Weight=4444

  Height=3333

  public class getProperties {

  public static void main(String[] args) throws FileNotFoundException, IOException {

  Properties pps = new Properties();

  pps.load(new FileInputStream("Test.properties"));

  Enumeration enum1 = pps.propertyNames();//得到配置文件的名字

  while(enum1.hasMoreElements()) {

  String strKey = (String) enum1.nextElement();

  String strValue = pps.getProperty(strKey);

  System.out.println(strKey + "=" + strValue);

  }

  }

  }

  3、一个比较综合的实例

  public class TestProperties {

  //根据Key读取Value

  public static 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);

  return value;

  }catch (IOException e) {

  e.printStackTrace();

  return null;

  }

  }

  //读取Properties的全部信息

  public static void GetAllProperties(String filePath) throws IOException {

  Properties pps = new Properties();

  InputStream in = new BufferedInputStream(new FileInputStream(filePath));

  pps.load(in);

  Enumeration en = pps.propertyNames(); //得到配置文件的名字

  while(en.hasMoreElements()) {

  String strKey = (String) en.nextElement();

  String strValue = pps.getProperty(strKey);

  System.out.println(strKey + "=" + strValue);

  }

  }

  //写入Properties信息

  public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {

  Properties pps = new Properties();

  InputStream in = new FileInputStream(filePath);

  pps.load(in);

  OutputStream out = new FileOutputStream(filePath);

  pps.setProperty(pKey, pValue);

  pps.store(out, "Update " + pKey + " name");

  }

  public static void main(String [] args) throws IOException{

  //String value = GetValueByKey("Test.properties", "name");

  //System.out.println(value);

  //GetAllProperties("Test.properties");

  WriteProperties("Test.properties","long", "212");

  }

  }

  结果:

  Test.properties中文件的数据为:

  #Update long name

  #Sun Feb 23 18:17:16 CST 2014

  name=JJ

  Weight=4444

  long=212

  Height=3333

  了解更多关于软件方面的知识,请访问上海软件培训学校

下一篇:Java Properties类
师资介绍