Apache Ant:添加和使用.txt文件

时间:2013-10-14 20:20:36

标签: java ant jar

我正在使用Apache Ant来编译,运行jar并为学校运行一个java项目。我遇到了一个问题,我不知道如何将单个.txt文件包含到我的.jar中,然后在我的java代码中引用它。

这是我的build.xml中的compile和jar命令。

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>
    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/BinaryTree.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="cs3345.MainLauncher"/>
            </manifest>
        </jar>
    </target>

我使用什么命令将.txt文件包含到我的jar中。我已经看过一些关于它的Stack Overflow问题,特别是

adding non-code resources to jar file using Ant

How can I include data text files in a jar using Ant?

但他们都没有真正解释如何包含文件。他们只是拥有对我来说没有意义的命令。我试过了,

        <jar destfile="build/jar/BinaryTree.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="cs3345.MainLauncher"/>
            </manifest>
            <fileset dir="src/resources" />
        </jar>

但这似乎没有帮助,因为我只是不理解Ant,我找不到实际解释为什么你在蚂蚁中做不同事情的文档。

我的.txt文件位于src / resources中。

3 个答案:

答案 0 :(得分:2)

<jar>任务任务多个文件集:

<jar destfile="build/jar/BinaryTree.jar" basedir="build/classes">
    <manifest>
        <attribute name="Main-Class" value="cs3345.MainLauncher"/>
    </manifest>
    <fileset dir="src/resources" />
</jar>

<manifest>任务是一个子实体。这非常像<manifest>任务。在你的jar中是一个名为META-INF/MANIFEST.MF的文件,这是为该jar添加另一个属性。这个特殊的属性告诉Jar什么是在jar被执行时应该启动的主类。

<fileset dir="src/resources"/> is adding all the files that are found in the resources`目录。如果您只想添加特定文件怎么办?您可以使用selectors。例如:

<jar destfile="build/jar/BinaryTree.jar" basedir="build/classes">
    <manifest>
        <attribute name="Main-Class" value="cs3345.MainLauncher"/>
    </manifest>
    <fileset dir="src/resources">
        <include name="foo.txt"/>
    </fileset>
</jar>

这次我没有添加整个resources目录树。我只是将一个名为foo.txt的文件添加到我的jar文件中。

答案 1 :(得分:1)

使用<copy>

<target name="copy" depends="blablabla" description="Copies additional files">
    <echo>Start Copying Files</echo>
    <copy file="./src/resources/a.txt" overwrite="true" todir="build/classes/"/>

    <echo>End Copying Files</echo>
</target>

作为旁注

如果我们想在src文件夹下包含一些文件,我们可以在target下写下:

            
              

答案 2 :(得分:1)

the documentation中没有任何内容表示“您只能添加.class文件”。 fileset标记应该有用。也许它把文件放在你不看的地方。以详细模式运行以确定它对.txt文件的作用。要控制目标,您应使用zipfileset标记。


  

但这似乎没有帮助。我的.txt文件位于,src / resources。

你将不得不详细说明。它怎么没帮忙?问题是文件是嵌套在zip下还是没有进入或者你有错误?