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

查看:48
本文介绍了如何获取 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天全站免登陆