Java:从文件系统加载资源 [英] Java: Loading resources from the file system

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

问题描述

我的项目设置

我有以下项目设置:

  \program.jar 
\images\logo.png

在我的代码中,我使用相对URL images / logo.png引用图片。




$ b 如果我在目录中使用以下命令运行此程序:
$ b
$ b

  c:\projects\program_dir\bin\> java -jar program.jar 

然后,一切正常,Java可以找到图像。



现在,我的问题是,我需要

  c:\> java -jar c:\ projects \program_dir\bin\program.jar 

程序执行完毕,但现在所有的相对网址不再有效。



我需要



如何计算program.jar文件的执行主目录,以便将相对URL更改为绝对URL?



这样你就不会不得不担心你的Jar从哪里启动。



然后你需要加载类似于下面的图片:

  InputStream stream = this.getClass()。getClassLoader()。 
getResourceAsStream(/ images / logo.png);


My Project Setup

I have the following project setup:

\program.jar  
\images\logo.png

In my code, I reference the image with the relative URL "images/logo.png".

Problem

If I run this program with the following command while in the directory:

c:\projects\program_dir\bin\>java -jar program.jar

Then everything works and Java is able to locate the image.

Now, my problem is, that I need to be able to run the program from a different directory.

c:\>java -jar c:\projects\program_dir\bin\program.jar

The program is executed, but now all the relative URLs no longer work.

What I need

How do I calculate the execution home of the program.jar file, so that I can change my relative URLs into absolute URLs?

解决方案

What I would do, if possible, is package your images in with your Jar.

That way you don't have to worry about where your Jar is launched from.

You would then need to load images similar to the following:

InputStream stream = this.getClass().getClassLoader().
                                     getResourceAsStream("/images/logo.png");

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

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