java修改properties配置文件中的内容
/**
* 修改properties配置文件中data_time的值
* @param bigtime 开始时间
* @param endtime 结束时间
* @throws IOException
*/
public static void getProperties(String bigtime,String endtime) throws IOException {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath().substring(1);
FileInputStream fis = new FileInputStream(path + "classes/email.properties");// 属性文件输入流
byte[] buf = new byte[fis.available()];
StringBuffer sb = new StringBuffer();
while ((fis.read(buf)) != -1) {
sb.append(new String(buf));
buf = new byte[1024];// 重新生成,避免和上次读取的数据重复
}
//得到修改后的字符串
StringBuffer pr = sb.replace(sb.indexOf("data_time")+10, sb.indexOf("#数据"), bigtime+"-"+endtime+"\r\n");
fis.close();// 关闭流
// 文件输出流
FileOutputStream fos = new FileOutputStream(path + "classes/email.properties");
// 将Properties集合保存到流中
fos.write(pr.toString().getBytes());
fos.close();// 关闭流
}
读取properties配置文件中的内容
public class PropertiesUtils {
private static final String LOCATION = "oao.properties";
private static Properties properties = new Properties();
/**
* 根据KEY获取参数
*
* @param key
* @return
*/
public static String getProperties(String key) {
String result = null;
InputStream input = null;
try {
input = PropertiesUtils.class.getClassLoader().getResourceAsStream(LOCATION);
properties.load(input);
result = properties.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
result = "";
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
result = "";
}
}
}
return result;
}
public static void main(String[] args) {
System.out.println(getProperties("ACCOUNT_PAGE_SIZE"));
}
}
oao.properties内容
ACCOUNT_PAGE_SIZE=20