今天使用Intellij Idea调试一段使用输入流加载properties配置文件的代码,代码以下:html
String propFileName = "config.properties"; InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(propFileName))); Properties props = new Properties(); if (null != inputStream) { props.load(inputStream); } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath."); }
运行时始终报系统找不到指定的文件异常:java
13:38:26.590 [main] WARN com.mikewoo.server.CentralSystemServer - load server config failed java.io.FileNotFoundException: config.properties (系统找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at com.mikewoo.server.config.ServerConfig.load(ServerConfig.java:51) at com.mikewoo.server.CentralSystemServer.main(CentralSystemServer.java:24)
可是文件路径和名字都没错,并且在eclipse下能正常运行,可在IEDA中就是报错。intellij-idea
后来受StackOverFlow上的一篇文章 Getting FileNotFoundException even though file exists and is spelled correctly的启发,在项目中输出配置文件的绝对路径和当前路径:eclipse
File file=new File("config.properties"); System.out.println(file.getAbsolutePath()); System.out.println(System.getProperty("user.dir"));
输出结果:ide
E:\program\ocpp-server\central-system-server\config.properties 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上面了,所以出现配置文件加载不到配置文件的缘由。idea
在IntelliJ IDEA中使用如上方式加载配置文件,是须要将启动配置中Working Directory选项的路径参数配置为$MODULE_WORKING_DIR$便可,示例设置以下图: spa