本地测试能跑通,打完jar包后部署到生产环境,报错找不到xxx.xxx配置文件。
例如获取配置文件下JDBC连接参数。写了个方法类。本地和linux服务器环境都能找到配置文件。
public class JdbcConfigReader {
public static void main(String[] args) {
Properties props = readConfigFile("jdbc.properties");
String driver = props.getProperty("jdbc.driver");
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
// Do something with the connection info
}
public static Properties readConfigFile(String filename) {
Properties props = new Properties();
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource(filename);
String resourcePath = resource.getPath();
InputStream inputStream = classLoader.getResourceAsStream(filename);
if (inputStream == null) {
inputStream = new FileInputStream(resourcePath);
}
props.load(inputStream);
inputStream.close();
} catch (IOException e) {
System.err.println("Failed to read config file " + filename + ": " + e.getMessage());
}
return props;
}
}