import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.Test;
public class PropertiesTest {
// 根据key读取value
public String readValue(String fileName, String key) {
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(this.getClass()
.getResourceAsStream(fileName));
props.load(in);
in.close();
String value = props.getProperty(key);
System.out.println(key + ":" + value);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Test
public void testReadValue() {
readValue("data.properties", "number");
}
// 读取properties的全部信息
public void readProperties(String fileName) {
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(this.getClass()
.getResourceAsStream(fileName));
props.load(in);
in.close();
Enumeration<?> en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty(key);
System.out.println(key + Property);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testReadProperties() {
readProperties("data.properties");
}
// 写入properties信息
public void writeProperties(String fileName, String parameterName,
String parameterValue) {
Properties prop = new Properties();
try {
//注意项目路径中不要有空格存在
String filePath = this.getClass().getResource(fileName).getPath().substring(1);
File file = new File(filePath);
if(!file.exists()){
System.out.println("file is null");
return;
}
InputStream fis = new BufferedInputStream(new FileInputStream(file));
// 从输入流中读取属性列表(键和元素对)
prop.load(fis);
fis.close();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(
file));
prop.setProperty(parameterName, parameterValue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
prop.store(fos, "Update '" + parameterName + "' value");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testWriteProperties() {
writeProperties("data.properties","test1","testValue");
}
}