Intellij Idea載入檔案出現FileNotFoundException 異常處理
阿新 • • 發佈:2018-12-04
問題描述
今天使用Intellij Idea除錯一段載入logback配置檔案的程式碼,程式碼如下:
public static void initLogback(String configFilepathName) { File file = new File(configFilepathName); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator joranConfigurator = new JoranConfigurator(); joranConfigurator.setContext(loggerContext); loggerContext.reset(); try { joranConfigurator.doConfigure(file); } catch (Exception e) { System.out.println(String.format("Load logback config file error. Message: ", e.getMessage())); } StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); }
執行時始終報系統找不到指定的檔案異常:
Load logback config file error. Message: 12:51:18,956 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml] 12:51:18,956 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy] 12:51:18,956 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.xml] 12:51:18,966 |-INFO in ch.qos.logback.classic.BasicConfigurator@2d38eb89 - Setting up default configuration. 12:51:19,046 |-ERROR in ch.qos.logback.classic.joran.JoranConfigurator@5fa7e7ff - Could not open [logback.xml]. java.io.FileNotFoundException: logback.xml (系統找不到指定的檔案。) at java.io.FileNotFoundException: logback.xml (系統找不到指定的檔案。) at at java.io.FileInputStream.open0(Native Method) at at java.io.FileInputStream.open(FileInputStream.java:195) at at java.io.FileInputStream.<init>(FileInputStream.java:138) at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:80)
但是檔案路徑和名字都沒錯,而且在eclipse下能正常執行,可在IEDA中就是報錯。
問題定位
後來受StackOverFlow上的一篇文章 Getting FileNotFoundException even though file exists and is spelled correctly的啟發,在專案中輸出配置檔案的絕對路徑和當前路徑:
File file=new File("logback.xml"); System.out.println(file.getAbsolutePath()); System.out.println(System.getProperty("user.dir"));
輸出結果:
E:\program\ocpp-server\central-system-server\logback.xml
E:\program\ocpp-server\central-system-server
仔細看輸出資訊發現,路徑定位的居然是Project路徑,而不是實際所在的Module路徑。這才使我想起來最開始學習使用時,IntelliJ IDEA官方一篇文章Migrating From Eclipse to IntelliJ IDEA中介紹過,IntelliJ IDEA中的Project,並不是真正的project,它其實跟eclipse中的workspace類似,在IntelliJ IDEA裡面“new Project”就相當於我們eclipse的“workspace”,而“new Module”才是建立一個工程。
然後檢視專案的啟動配置,發現Working Directory中配置的路徑果然指到的是Project上面了,這就是為什麼載入不到配置檔案的原因。
解決方案
在IntelliJ IDEA中使用如上方式載入配置檔案,是需要將啟動配置中Working Directory選項的路徑引數配置為$MODULE_WORKING_DIR$即可,示例設定如下圖: