运行时, 目录结构如下:
.
|-- ./build
| `-- ./build/TestAntLoadFile.class
|-- ./build.xml
|-- ./dist
| |-- ./dist/icpFinder.jar
| `-- ./dist/icp-finder.properties
|-- ./icp-finder_bak.properties
`-- ./src
`-- ./src/TestAntLoadFile.java
可运如何代码时,
public class TestAntLoadFile {
private static final String CUSTOMER_CONFIG_FILE_NAME = "icp-finder.properties";
public static void main(String[] args) {
InputStream custumerConfigIn = TestAntLoadFile.class.
getClassLoader().getResourceAsStream(CUSTOMER_CONFIG_FILE_NAME);
System.out.println("custumerConfigIn: " + custumerConfigIn);
}
}
build.xml中核心配置如下:
<path id="run.classpath">
<fileset dir = "${dist.dir}" >
<include name="**/*.jar"/>
<include name="**/*.properties"/>
<include name="./icp-finder.properties"/>
</fileset>
</path>
<target name="run" depends="jar">
<java fork="true" classname="TestAntLoadFile">
<classpath>
<path refid="run.classpath"/>
</classpath>
</java>
</target>
显示结果:custumerConfigIn: null。
这是为什么? 我知道是ant脚本里写的可能有问题。 同样的代码在Eclipse中运行时显示是没问题的。
实验代码见附件。
本文探讨了一段使用Ant构建工具的代码,在运行时无法正确加载配置文件的原因,重点关注类加载器的作用及路径配置对资源访问的影响。通过对比Eclipse运行环境,揭示了Ant脚本中`build.xml`配置与类路径设置的不当之处,并提供了解决方案。
221

被折叠的 条评论
为什么被折叠?



