标签:java 解析配置文件 properties xml
1. 利用java.util提供的工具类Properties
- 首先我这边有个file.properties文件
- 然后去读取这个文件
注意项目路径
//注意ProConfigUtil是当前类,也可用this替代
InputStream inputStream = PropConfigUtil.class.getClassLoader()
.getResourceAsStream("config/file.properties");
Properties pro = new Properties();
pro.load(inputStream);
String fileType = pro.getProperty("file.fileType").trim();
完整代码
package com.zsl.uploadfile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.configuration.ConfigurationException;
public final class ImagePropConfigUtil
{
public ImagePropConfigUtil()
{}
public static class SingleTon
{
private static InputStream inputStream = null;
private static Properties pro = null;
static
{
inputStream = ImagePropConfigUtil.class.getClassLoader().getResourceAsStream(
"config/file.properties");
pro = new Properties();
try
{
pro.load(inputStream);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static String getVal(String key)
{
return SingleTon.pro.getProperty(key);
}
public static void main(String[] args)
throws ConfigurationException
{
System.out.println("--------------------");
String val = ImagePropConfigUtil.getVal("file.fileType");
System.out.println("-------文件类型为:\t" + val);
}
}
2.利用jar包:Apache-commons-configuration-1.5.jar
PropertiesConfiguration prop = new PropertiesConfiguration("config/file.properties");
prop.setDelimiterParsingDisabled(true);
String val = prop.getProperty("image.imageType").toString();
System.out.println(val);
完整代码
package com.zsl.uploadfile;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class Util
{
public Util()
{}
public static class Single
{
private static PropertiesConfiguration prop = null;
static
{
try
{
prop = new PropertiesConfiguration("config/file.properties");
prop.setDelimiterParsingDisabled(true);
}
catch (ConfigurationException e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public static String getVal(String key)
{
String value = Single.prop.getProperty(key).toString();
return value;
}
public static void main(String[] args)
{
System.out.println(Util.getVal("file.fileType"));
}
}
上面这两种方法就可以读取配置文件。相比较而言比较高效率的读取配置文件,模拟单例模式,程序只调用一次,
打印结果如下:
标签:java 解析配置文件 properties xml
原文地址:http://blog.csdn.net/moyanxuan_1993_2_24/article/details/45722513