package com.properties.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesUnit
{
private String filename;
private Properties properties;
private FileInputStream in;
private FileOutputStream out;
public PropertiesUnit()
{
properties = new Properties();
}
public PropertiesUnit(String filename)
{
this.filename = filename;
properties = new Properties();
File file = new File(filename);
try
{
in = new FileInputStream(file);
properties.load(in);
in.close();
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
}
}
public String getValue(String key)
{
if(properties.containsKey(key))
{
String value = properties.getProperty(key);
return value;
}
else
{
return "";
}
}
public String getValue(String fileName,String key)
{
try
{
String value="";
in = new FileInputStream(fileName);
properties.load(in);
in.close();
if(properties.containsKey(key))
{
value = properties.getProperty(key);
return value;
}
else
{
return value;
}
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
return "";
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
return "";
}
}
public void clear()
{
properties.clear();
}
public void setValue(String key,String value)
{
properties.setProperty(key,value);
}
public void saveFile(String fileName,String description)
{
try
{
out = new FileOutputStream(fileName);
properties.store(out,description);
out.close();
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
}
}
public static void main(String[] args)
{
PropertiesUnit pu = new PropertiesUnit("./config.properties");
String key = pu.getValue("key");
System.out.println(key);
}
}
java读取properties文件
原创
©著作权归作者所有:来自51CTO博客作者mb64660286caedc的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:在servlet中获得项目路径
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java读取properties文件配置
java读取properties文件配置
java properties 文件配置 -
[java基础]读取properties文件
java基础 读取properties文件
properties文件 加载 输入流 Java