很久以前保存的网页,源地址不记得了,在我的环境中把代码敲了一遍。
配置文件叫做:ipConfig.properties,里面有两行内容:
ip=127.0.0.1
port=8080
配置文件叫做:ipConfig.properties,里面有两行内容:
ip=127.0.0.1
port=8080
package cn.treemp3.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
*
* @author yangfusheng9
*/
public class PropertiesTest {
private Properties properties;
public PropertiesTest() {
properties = new Properties();
}
public PropertiesTest(String file) {
properties = new Properties();
try {
FileInputStream inputFile = new FileInputStream(file);
properties.load(inputFile);
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("读取属性文件失败!可能原因:文件路径错误或者文件不存在");
e.printStackTrace();
} catch (IOException e) {
System.out.println("装载文件失败!");
e.printStackTrace();
}
}
public String getValue(String key) {
if (properties.containsKey(key)) {
String value = properties.getProperty(key);
return value;
} else {
return "";
}
}
public void clear() {
properties.clear();
}
public void setValue(String key, String value) {
properties.setProperty(key, value);
}
public void saveFile(String file, String description) {
try {
FileOutputStream outputFile = new FileOutputStream(file);
properties.store(outputFile, description);
outputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
PropertiesTest test = new PropertiesTest("ipConfig.properties");
String ip = test.getValue("ip");
String port = test.getValue("port");
System.out.println("ip: " + ip);
System.out.println("port: " + port);
test.setValue("host", "localhost");
test.saveFile("save.properties", "test");
}
}