创建包含外部文件的 Runnable Jar [英] Creating Runnable Jar with external files included

查看:38
本文介绍了创建包含外部文件的 Runnable Jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用java构建一个可运行的jar.我需要在 jar 中包含一些文件,以便当我执行 jar 时,这些文件会自动从 java 类中读取.因此我在项目中创建了一个文件夹并从项目中引用了这些文件.我按照一些教程创建了 jar 文件,但我无法在我的 jar 文件中包含这些外部文件.请让我了解如何使用外部文件创建可运行的 jar.

I want to build a runnable jar in java. I need to include some of the files in the jar so that when I execute jar the files are automatically read from the java class. Hence I created a folder in the project and referred these files from the project. I created jar file following some tutorial but I could not able to include these external files in my jar file. Please let me about creating runnable jar with external files.

我的文件结构是

Test
|
|
-------src
|        |
|        default package
|                      |
|                      |
|                      test1.java
|
 -------FileFOlder
|              |
|              | 
|              abc.txt

我正在test1.java 类中访问abc.txt.我的代码是,

I am accessing abc.txt in test1.java class. My code is,

public class test1 {


public static void main(String[] args) throws IOException {


    char [] read = new char[20];
    String path = new File(".").getCanonicalPath();
    path = path+"\Newfolder\abc.txt";
    System.out.println(path);
    File nF = new File(path);
    FileReader fR = new FileReader(nF);
    fR.read(read);
    for(char c : read){
        System.out.print(c);
    }
    fR.close();
    System.out.println(" Hi..This is test program ");
}

}

当我使用 eclipse 导出选项创建可执行 jar 时,我看不到 jar 中的 FileFolder 目录.请给我一些关于这方面的信息.

When I create executable jar using eclipse export option, I am unable to see FileFolder directory inside the jar. Please give me some information regarding this.

推荐答案

您应该这样做:

将该文件放回您的 jar 文件中.使用 class.getResourceAsStream() 代替 FileFileReader 来读取它.以下是如何做到这一点的说明:如何真正从 Java 中的类路径读取文本文件

Put that file back in your jar file. Use class.getResourceAsStream() to read it instead of File and FileReader. Here is an explanation of how to do that: How to really read text file from classpath in Java

这篇关于创建包含外部文件的 Runnable Jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆