如何在.jar中获取资源?

时间:2014-01-19 21:47:26

标签: java jar

我使用this HttpServer类。 如何将WEB_ROOT设置为.jar文件中的资源?

我试图这样做,

static final File WEB_ROOT = new File(HttpServer.class.getResource("www"));

但我有错误“找不到适合文件(URL)的构造函数。”

Compilaton

~$ javac HttpServer.java

创建jar文件

~$ jar cfe http.jar HttpServer HttpServer.class ./www/

我做错了什么?

1 个答案:

答案 0 :(得分:0)

要检索jar中的文件,请使用:

InputStream is = HttpServer.class.getResourceAsStream("www");

替代地

      static File WEB_ROOT = null;
static {
    try {
        WEB_ROOT = new File(HttpServer.class.getResource("www").toURI());
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

但不要把它变成静态。