【问题标题】:Include external file (not jar) to executable jar将外部文件(不是 jar)包含到可执行 jar 中
【发布时间】:2015-03-02 21:31:11
【问题描述】:

如果我将一些(比如 *.txt)文件加载到我的 java 应用程序中,我如何将它包含到我的最终可执行 jar 中以使其可移植(这意味着如果我将我的 jar 移动到另一台机器上,则不需要移动它 * .txt 文件)?

请注意,我不需要文件的内容,我需要文件本身。以及我应该如何从代码中写入这个文件的路径?

String path = "path/to/file/"; //Yeah it should be String

我正在使用 IntellijIDEA,我可以将任何文件包含到我的最终 jar 中,但不知道放置它的位置。谢谢。

【问题讨论】:

标签: java jar executable-jar


【解决方案1】:

你需要像下面这样的东西

<target name="somejar" depends="compile">
      <jar jarfile="${somejar.jar}">
        <fileset dir="${bin.dir}">
          <include name="**/*.class"/>
        </fileset>
        <zipgroupfileset dir="lib" includes="*.jar"/>
        <fileset dir="${basedir}">
          <include name="config/*.properties"/>
          <include name="config/*.txt"/>
        </fileset>
      </jar>
    </target>

这会将所有需要的类和属性文件放在一起。您可以从项目的基础编写文件的位置,直到您到达文件。

【讨论】:

    【解决方案2】:

    只需将您的文件放入项目的 src 文件夹 - 例如 src/resource/file.txt。当您构建项目时,整个 src 内容将被放入生成的 jar 中。您可以使用以下代码访问您的文件:

    this.getClass().getResource("/resource/file.txt");    
    

    读取所有行的示例:

    URL url = this.getClass().getResource("/resource/file.txt");
    Path path = Paths.get(url.toURI());
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);    
    

    【讨论】:

    • 感谢您的意见。但我的函数等待string 格式文件路径作为参数。使用toString() 我得到像file:/full/path/to/file/ 这样的字符串,所以它对我不可用。
    • 非常感谢!你拯救了我的一天
    猜你喜欢
    • 2013-08-16
    • 2011-09-18
    • 2013-06-08
    • 2014-09-27
    • 1970-01-01
    • 2013-08-08
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多