我刚刚开始使用 Ant,但在让“运行”目标工作时遇到了问题。我的部分代码加载了一个属性文件,它总是找不到这个文件,除非我让我的运行目标使用新的 JVM。下面是一个非常简化的示例,“run”目标失败,“run_fork”目标有效。我的理解是 Ant 有它自己的类加载器来替换默认的类加载器,所以我想这在某种程度上与搜索路径混淆了。有什么方法可以更改我的代码以使其工作而无需分叉一个新的 JVM?
构建.xml:
<project name="PropsExample" default="compile" basedir=".">
<property name="src" location="src"/>
<property name="bin" location="bin"/>
<target name="init">
<tstamp/>
<mkdir dir="${bin}"/>
</target>
<target name="compile" depends="init">
<javac includeAntRuntime="false" srcdir="${src}" destdir="${bin}"/>
<copy todir="${bin}">
<fileset dir="${src}" includes="**/*.properties"/>
</copy>
</target>
<target name="clean">
<delete dir="${bin}"/>
<delete dir="${dist}"/>
</target>
<target name="run" depends="compile">
<java classname="com.example.Test">
<classpath>
<pathelement location="${bin}"/>
</classpath>
</java>
</target>
<target name="run_fork" depends="compile">
<java fork="true" classname="com.example.Test">
<classpath>
<pathelement location="${bin}"/>
</classpath>
</java>
</target>
示例代码:
package com.example;
import java.util.Properties;
import java.io.InputStream;
public class PropertiesLoader {
public static String getProperty() throws Exception {
InputStream in = ClassLoader.getSystemResourceAsStream("com/example/test.properties");
if ( in == null ) {
throw new Exception("Cannot find test.properties");
}
Properties p = new Properties();
p.load(in);
in.close();
return p.getProperty("test");
}
}
和:
package com.example;
public class Test {
public static void main(String[] args) throws Exception {
try {
System.out.println(PropertiesLoader.getProperty());
} catch ( Exception e ) {
e.printStackTrace(System.out);
}
}
}