-----------------------------------------------------------------------------------------
部署的时候,配置文件可以放在与运行jar 同级目录、config目录下。
开发时候可以放在 项目resources 下 ,或者resources/config 下。
调用findFile 查找文件。
调用 loadProperties 加载properties 文件。
调用 findConfigFilePath 查找文件路径。
----------------------------------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 配置文件工具类。
*
*/
public class ConfigUtil {
static Logger log=LoggerFactory.getLogger(ConfigUtil.class);
public static void main(String[] args) {
String path=findConfigFilePath("apiclient_key.pem");
System.out.println(path);
}
static String classRootPath;
static {
try {
classRootPath= ConfigUtil.class.getResource("/").getPath();//获取类路径根目录
}catch(Exception e) {
log.info("--->--->--->没有找到classes路径,如果项目已经部署请无视。");
classRootPath=null;
}
}
/**
* 加载properties文件
*
* @param name
* @return
*/
public static Properties loadProperties(String name) {
try {
InputStream is = new FileInputStream(findConfigFile(name));
Properties pro = new Properties();
pro.load(is);
is.close();
return pro;
} catch (Exception e) {
throw new RuntimeException("加载文件Properties异常,文件名:" + name, e);
}
}
/**
* 查找配置文件。分别在平级目录、config、配置文件根目录、配置文件config,逐级查找 。 找到则返回File ;否则抛出
* RuntimeException(没有找到文件)
*
* @param name 文件名字
* @return
*/
public static File findConfigFile(String name) {
File f = findFile(name, StringUtil.append("config/", name));
if(classRootPath==null) {
return f;
}
f= findFile(
StringUtil.append(classRootPath, name), // 类路径:name
StringUtil.append(classRootPath, "config/", name)); // 类路径:/config/name
if(f==null) {
throw new RuntimeException("没有找到配置文件:"+name);
}
return f;
}
/**
* 查找配置文件路径。分别在平级目录、config、配置文件根目录、配置文件config,逐级查找 。 找到则返回文件路径 ;否则抛出
* RuntimeException(没有找到文件)
*
* @param name 文件名字
* @return
*/
public static String findConfigFilePath(String name) {
File f = findConfigFile(name);
return f.getPath();
}
/**
* 查找文件. 找不到返回null
*
* @param paths
* @return
*/
public static File findFile(String... paths) {
File f = null;
for (String path : paths) {
f = findFile(path);
if (f != null) {
return f;
}
}
return null;
}
private static File findFile(String pathname) {
File f = new File(pathname);
if (f.exists()) {
return f;
}
return null;
}
}