java 属性文件(配置文件)的操作

很久以前保存的网页,源地址不记得了,在我的环境中把代码敲了一遍。
配置文件叫做: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");
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值