您的位置:首页 > 移动开发 > Objective-C

OOP(Object Oriented Progamming )面向对象的程序设计

2014-02-10 22:34 489 查看
太无聊了,写个读properties文件的类方便以后直接copy
private String fileName;
private Properties properties;
private FileInputStream inputFile;
private String filePath;

// Constructor
public ProUtil() {
this.properties = new Properties();
}

// get path of property file
public String getConfigPath() {
String strClassName = getClass().getName();
String strPackageName = "";
if (getClass().getPackage() != null) {
strPackageName = getClass().getPackage().getName();
}
String strClassFileName = "";
if (!"".equals(strPackageName)) {
strClassFileName = strClassName.substring(
strPackageName.length() + 1, strClassName.length());
} else {
strClassFileName = strClassName;
}
URL url = null;
url = getClass().getResource(strClassFileName + ".class");
String strURL = url.toString();
try {
strURL = java.net.URLDecoder.decode(strURL, "UTF-8");
System.out.println("strURL  :  " + strURL);
} catch (Exception ex) {
ex.printStackTrace();
}
strURL = strURL.substring(strURL.indexOf('/') + 1,
strURL.lastIndexOf('/') + 1);
return strURL;
}

// file configuration
private void initFileConfig() {
try {
filePath = this.getConfigPath();
filePath += fileName;
System.out.println("filePath is : " + filePath);
inputFile = new FileInputStream(filePath);
properties.load(inputFile);
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("配置文件路径错误");
} catch (IOException e) {
System.out.println("配置文件度取失败");
} catch (Exception ex) {
ex.printStackTrace();
}
}

// read Value by key from input parameter "fileName"
public String readValueByKey(String fileName, String key) {
try {
String value = "";
this.fileName = fileName;
initFileConfig();
if (properties.containsKey(key)) {
value = properties.getProperty(key);
return value;
} else
return value;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}

// read all info from property file
public String readAllValues(String fileName) {

try {
@SuppressWarnings("rawtypes")
Enumeration en = properties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = properties.getProperty(key);
System.out.println("Key is : " + key + "  Value is : " + value);
}
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
return null;
}

// read Value by key
// public String getValue(String key) {
// if (propertie.containsKey(key)) {
// String value = propertie.getProperty(key);
// return value;
// } else {
// return "";
// }
// }
//test
public static void main(String[] args) {
ProUtil property = new ProUtil();
System.out.println(property.readValueByKey("xxx.properties",
"a"));
System.out.println(property.readAllValues("xxx.properties"));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: