java读取properties文件内容,做网站的时候,经常会把一些基本配置,写到properties文件里。如果要修改这些基本配置,就只要修改此文件就行了,不用修改java文件。
下面是读取properties文件内容的代码:
其中,有一个config.properties文件,放在classes目录里,文件内容如下:
下面是读取properties文件内容的代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 读取Properties配置文件信息
* @author sunlightcs
* 2011-5-2
* http://hi.juziku.com/sunlightcs/
*/
public class PropertiesFile {
private static Logger logger = Logger.getLogger(PropertiesFile.class);
/**
* 读取Properties配置文件
* @return 返回Properties数据
*/
public Properties getPropertiesFile(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream("config.properties");
Properties prop = new Properties();
try {
prop.load(is);
is.close();
} catch (IOException ex) {
logger.error("读取配置文件失败,配置文件路径为:config.properties", ex);
}
return prop;
}
/**
* 读取Properties配置文件
* @param filePath 配置文件路径
* @return 返回Properties数据
*/
public Properties getPropertiesFile(String filePath){
InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
Properties prop = new Properties();
try {
prop.load(is);
is.close();
} catch (IOException ex) {
logger.error("读取配置文件失败,配置文件路径为:"+filePath, ex);
}
return prop;
}
public static void main(String[] args){
Properties prop = new PropertiesFile().getPropertiesFile();
String path = prop.getProperty("imagePath");
System.out.println(path);
}
}
其中,有一个config.properties文件,放在classes目录里,文件内容如下:
#图片路径
imagePath=D:\\www\\imagePath