模拟试题

3773考试网计算机等级考试模拟试题正文

2011计算机二级JAVA编程:从资源文件里读取值的类

来源:fjzsksw.com 2010-11-4 14:30:30

 

 

  从资源文件里读取值的类

  从资源文件里读取值的类,文件后缀不一定要.Properties,只要里面内容如:url=www.cnsec.net

  可通过key(url)取得值-www.cnsec.net,简单、强大

  Java code

  import java.io.File;

  import java.io.FileInputStream;

  import java.io.FileNotFoundException;

  import java.io.IOException;

  import java.util.Properties;

  /**

  * ReadProperties.java

  * Description: 读取操作属性配置文件

  * @author li.b

  * @version 2.0

  * Jun 26, 2008

  */

  public class ReadProperties {

  /**

  * Description: 获取属性配置文件

  * @param path 资源文件路径

  * @return Properties Object

  * @throws FileNotFoundException

  * @throws IOException

  */

  public static Properties getProperties(String path) throws FileNotFoundException, IOException{

  Properties props = null;

  File file = new File(path);

  if(file.exists() && file.isFile()){

  props = new Properties();

  props.load(new FileInputStream(file));

  }else{

  System.out.println(file.toString() + "不存在!");

  }

  return props;

  }

  /**

  * Description: 从属性文件获取值

  * @param props Properties Object

  * @param key

  * @return 通过key匹配到的value

  */

  public static String getValue(Properties props,String key,String encod){

  String result = "";

  String en = "";

  String localEN = System.getProperty("file.encoding");

  if(encod !=null && !encod.equals("") ){

  en = encod;

  }else{

  en = localEN;

  }

  try {

  key = new String(key.getBytes(en),"ISO-8859-1");

  result = props.getProperty(key);

  if(!result.equals("")){

  result = new String(result.getBytes("ISO-8859-1"),en);

  }

  } catch (Exception e) {

  }finally{

  if(result == null)result = "";

  return result;

  }

  }

  public static String getValue(Properties props,String key){

  return getValue(props, key, "");

  }

  }

 

 

触屏版 电脑版
3773考试网 琼ICP备12003406号-1