在Jar中加载资源 [英] Load a resource in Jar

查看:73
本文介绍了在Jar中加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的Jar文件的结构

root
 - template.ftl
 - org.project.myproject.App.java

在App.java中,我有一行代码希望我指定directory来加载template.ftl.像这样:

Inside App.java, I have a line of code that expects me to specify the directory for loading the template.ftl. Something like:

Line#1: cfg.setDirectoryForTemplateLoading("java.io.File object that represents /directory/for/storing/template/files");

和下一行代码,读取模板文件

and the next line of code, read the template file

Line#2: Template temp = cfg.getTemplate("template.ftl");

我的问题是我无法指定将从中加载文件的目录路径. Jar的根目录中提供了要加载的模板文件.我写的时候,

My problem is that I'm not able to specify the path of directory from where the file will be loaded. The template file to load is available in root of the Jar. When I write,

cfg.setDirectoryForTemplateLoading(new File("."));

它说,没有找到template.ftl.

可以正确设置上面Line#1处的模板目录的适当代码是什么?

What should be apprpriate code that can set the template directory correctly at Line#1 above?

推荐答案

我认为这对您不起作用,因为您正在尝试加载一个不存在的文件,但该文件位于jar中.要从jar文件中读取模板作为输入流,可以执行以下操作:

I think this isn't working for you because you're trying to load a file that doesn't exist as a file but is inside your jar. To read your template as an input stream from within the jar file you could do:

this.getClass().getClassLoader().getResourceAsStream("template.ftl");

我认为这应该有助于您进入正确的轨道.

I think this should help get you onto the right track.

这篇关于在Jar中加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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