Gradle加载properties文件时忽略FileNotFoundException的实现方法
解决build.gradle加载properties文件时文件不存在导致编译失败的问题
嘿,这个问题我之前配置项目的时候也踩过坑!其实只要给你的加载逻辑加上完整的异常捕获,同时确保默认值能正常兜底,就能实现不管文件存不存在都顺利编译啦。
方案一:先检查文件存在性再加载(更高效)
先判断文件是否存在,避免不必要的异常抛出,再在try-catch里处理加载过程中可能出现的其他IO错误:
def Properties properties = new Properties() // 获取文件对象 def developerPropsFile = project.rootProject.file("developer.properties") if (developerPropsFile.exists()) { try { properties.load(developerPropsFile.newDataInputStream()) } catch (IOException e) { // 打印警告但不中断编译,方便排查问题 logger.warn("加载developer.properties文件失败: ${e.message}") } } android { defaultConfig { // 用getOrDefault确保没加载到属性时也有默认值 buildConfigField 'boolean', 'PrintLog', properties.getOrDefault("print.log", "false") } }
方案二:直接捕获所有IO异常(更简洁)
如果不想额外做存在性检查,也可以直接捕获文件不存在和加载失败的异常,一样能保证编译继续:
def Properties properties = new Properties() try { properties.load(project.rootProject.file("developer.properties").newDataInputStream()) } catch (FileNotFoundException e) { // 文件不存在时打印提示,用默认配置 logger.info("developer.properties文件不存在,将使用默认配置") } catch (IOException e) { // 其他加载错误打印警告 logger.warn("加载developer.properties文件出错: ${e.message}") } android { defaultConfig { buildConfigField 'boolean', 'PrintLog', properties.getOrDefault("print.log", "false") } }
核心要点说明
- 异常捕获:关键是捕获
FileNotFoundException(文件不存在)和IOException(其他加载错误),并且不要抛出这些异常,而是用logger打印提示,这样编译流程不会被中断。 - 默认值兜底:使用
properties.getOrDefault()方法,确保即使properties对象是空的,也能拿到预设的默认值,避免出现null导致的其他问题。
这样修改后,不管developer.properties文件是否存在,项目都能正常编译,文件存在时加载自定义配置,不存在时就用默认的false值。
内容的提问来源于stack exchange,提问作者Youngjae
相关产品推荐
相关产品推荐

