package com.appium.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
/**
* @author YuFeifei
* @version 2017年11月15日 上午8:59:54
* 类说明:
* 读取配置文件中的key和value;
* 2个方法:通过key获取value、往配置文件写入key和value
*/
/**读取配置文件*/
public class ProUtilTest {//工具类
/**属性1-文件存储路径*/
private String filePath;
/**属性2-Properties类,是Map的子类,用于读取和存储key和value*/
private Properties prop;
/**构造方法*/
public ProUtilTest(String filePath){
this.filePath = filePath;
this.prop = readProperties();//下面写的方法
}
/**方法:将key和value读取并放入properties中*/
public Properties readProperties(){
Properties properties = new Properties();
try{
InputStream ins = new FileInputStream(filePath);
BufferedReader bf = new BufferedReader(new InputStreamReader(ins, "utf-8"));
properties.load(bf);
ins.close();
} catch (Exception e){
e.printStackTrace();
}
return properties;
}
/**方法:通过key获取value*/
public String getProp(String key){
if (prop.containsKey(key)){
return prop.getProperty(key);
}else{
System.out.println("获取的键不存在!");
}
return "";
}
/**方法:写入key和value*/
public void setProp(String key,String value){
if(prop == null){
prop = new Properties();
}
try {
OutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream,"utf-8"));
prop.setProperty(key, value);
prop.store(bw, key + "value");//第二个参数是配置文件的注释
bw.close();
outputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
/**测试*/
public static void main(String agrs[]){
//ProUtilTest firstTest = new ProUtilTest("./configs/test1.properties");
//firstTest.getProp("Enter_home_page");
//System.out.println(firstTest.getProp("Enter_home_page"));
ProUtilTest firstTest = new ProUtilTest("./configs/testnull.properties");
firstTest.setProp("Enter_home_page", "name>进入");
}
}