简体   繁体   English

ClassLoader.getResourceAsStream在JAR文件中找不到资源

[英]ClassLoader.getResourceAsStream can't find resource in JAR file

I have a Java project in Eclipse with several classes with main methods, and a resource folder with properties. 我在Eclipse中有一个Java项目,其中有几个具有主要方法的类,以及一个具有属性的资源文件夹。 The resource folder, which contains 'config/config.properties', is in the Build Path (right-click the resource folder in Project Explorer in Eclipse->Build Path->Add to Build Path). 资源文件夹包含“ config / config.properties”,位于构建路径中(在Eclipse->构建路径->添加到构建路径中的Project Explorer中,右键单击资源文件夹)。 I can run the classes with main methods fine from Eclipse and the resources are properly loaded. 我可以使用Eclipse中的主要方法运行类,并且可以正确加载资源。 I am generating a runnable JAR file from one of the classes with a main method (right-click on the Java class file in Package Explorer->Export->Java/Runnable JAR file). 我正在使用一种主要方法从一个类中生成一个可运行的JAR文件(在Package Explorer-> Export-> Java / Runnable JAR文件中右键单击Java类文件)。 When I execute the JAR file ('java -jar myApp.jar') ClassLoader.getResourceAsStream("config/config.properties") returns null. 当我执行JAR文件('java -jar myApp.jar')时,ClassLoader.getResourceAsStream(“ config / config.properties”)返回null。 I have tried prepending several numbers of '../' to the properties file path but (1) this does not work and (2) it breaks execution for running in Eclipse. 我尝试在属性文件路径前添加多个“ ../”,但是(1)这不起作用,(2)中断了在Eclipse中运行的执行。 The application takes no parameters on the command line. 该应用程序在命令行上不接受任何参数。 Any ideas what the problem is? 任何想法是什么问题?

Do you have a META-INF/MANIFEST.MF file in your jar? 您的jar中是否有META-INF/MANIFEST.MF文件?

Add the following line to the file: 将以下行添加到文件中:

Class-Path: .

Don't forget an empty line after that. 之后不要忘了空行。 I had a similar problem a couple of years ago. 几年前,我遇到了类似的问题。

More info on the manifest.mf file 有关manifest.mf文件的更多信息

Try exporting the jar using the Jar Export Wizard. 尝试使用Jar导出向导导出jar。 You can open it by right clicking -> "Export" -> "Jar file" (as opposed to "Runnable JAR file"). 您可以通过右键单击->“导出”->“ Jar文件”(而不是“可运行的JAR文件”)来打开它。

This will allow you to individually select each file you want to include. 这将允许您单独选择要包括的每个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM