您的位置:首页 > 编程语言 > Java开发

Java操作属性文件

2013-12-30 22:01 387 查看
1、读取属性文件

/**
* 读取属性值
* @param filePath
* @param key
* @param defValue
* @return
*/
public String read(String filePath, String key, String defValue)
{
Properties props = new Properties();
try
{
// 如果文件不存在,返回默认值
File file = new File(filePath);
if (!file.exists())
{
return defValue;
}
InputStream fis = new FileInputStream(filePath);
props.load(fis);
fis.close();
return props.getProperty(key) == null ? defValue : props.getProperty(key);
}
catch (IOException e)
{
System.out.println("读取文件出错了:" + e);
return defValue;
}
}


2、写入属性文件

/**
* 写入属性值
* @param filePath
* @param key
* @param value
*/
public boolean write(String filePath, String key, String value)
{
Properties props = new Properties();
try
{
// 如果文件不存在,创建一个新的
File file = new File(filePath);
if (!file.exists())
{
file.createNewFile();
}
InputStream fis = new FileInputStream(filePath);
props.load(fis);
fis.close(); // 关闭流
OutputStream fos = new FileOutputStream(filePath);
props.setProperty(key, value);
props.store(fos, key);
fos.close(); // 关闭流
return true;
}
catch (FileNotFoundException e)
{
System.out.println("文件不存在!");
}
catch (IOException e)
{
System.out.println("写入文件出错了:" + e);
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: