获取properties文件的信息
代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取配置文件信息工具类
*
* @author
*
*/
public class PropertiesUtil {
/**
* 获取某配置文件的值 带默认值
*
* @param url
* properties文件名路劲
* @param propName
* 获取关键字
* @param defaultValue
* 默认值
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static String loadProperties(String url, String propName, String defaultValue)
throws FileNotFoundException, IOException {
Properties prop = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(url);
prop.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String returnValue = prop.getProperty(propName, defaultValue);
return returnValue;
}
/**
* 获取某配置文件的值 不带默认值
*
* @param fileName
* 配置文件名
* @param key
* 获取关键字
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static String getProperty(String fileName, String key) {
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName);
System.out.println(in == null ? "in=null" : in.toString());
try {
prop.load(in);
String value = prop.getProperty(key);
return value;
} catch (IOException e) {
e.printStackTrace();
return "false";
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取某配置文件的所有值
*
* @param fileName
* 配置文件名
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public Properties getProperties(String fileName) {
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName);
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println(PropertiesUtil.getProperty("ConstVar.properties", "FILE_UPLOAD_DIR"));
}
}
在src/main/resource/ConstVar.properties如图:
运行结果: