如何获取Java JAR文件中的资源路径 [英] How to get a path to a resource in a Java JAR file

查看:160
本文介绍了如何获取Java JAR文件中的资源路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到资源的路径,但我没有运气。

I am trying to get a path to a Resource but I have had no luck.

这适用于(在IDE和JAR中)但这样我无法获得文件的路径,只有文件内容:

This works (both in IDE and with the JAR) but this way I can't get a path to a file, only the file contents:

ClassLoader classLoader = getClass().getClassLoader();
PrintInputStream(classLoader.getResourceAsStream("config/netclient.p"));

如果我这样做:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config/netclient.p").getFile());

结果是:
java.io.FileNotFoundException:file :/ path/to/jarfile/bot.jar!/config/netclient.p(没有这样的文件或目录)

有没有获取资源文件路径的方法?

Is there a way to get a path to a resource file?

推荐答案

这是故意的。 文件的内容可能无法作为文件提供。请记住,您正在处理可能属于JAR文件或其他类型资源的类和资源。类加载器不必为资源提供文件句柄,例如jar文件可能没有扩展到文件系统中的单个文件中。

This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.

你能做什么如果绝对需要java.io.File,可以通过将流复制到临时文件并执行相同的操作来获取java.io.File。

Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.

这篇关于如何获取Java JAR文件中的资源路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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