Specifying classpath for a jar

半世苍凉 提交于 2019-12-01 04:30:01

问题


I am trying to configure the classpath of a JAR so that my ResourceBundle can pick up property files from it.

If I run it from the .class files and specify the -cp flag it works fine, and System.err.println(System.getProperty("java.class.path")); will print the path specified in the -cp flag.

If I try and create a jar file for it, System.err.println(System.getProperty("java.class.path")); always prints the path of the jar file, and the property files aren't picked up.

It seems if you are running it as a jar file you can't specify the -cp flag (which was what I was hoping, as it's common to switch which property files are being used). I've tried specifying it in the jar manifest instead, but it's still not working.

Here is the code and manifest from a test jar that doesn't seem to work:

public final class Test {
    public static void main(final String[] args) {
        System.err.println(System.getProperty("java.class.path"));
    }
}

 

Manifest-Version: 1.0
Created-By: 1.6.0_20 (Sun Microsystems Inc.)
Main-Class: Test
Class-Path: /home/ajanuary/Projects/test/

edit The original path was rather meaningless so I changed it. I want to point to a directory which the ResourceBundle can find the property files in.


回答1:


If you use -jar, -cp is ignored:

-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests. When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

Source: java - the Java application launcher




回答2:


I would instead read a property in my Java application (that property could indicate from where resources should be loaded).

Example of how to execute the application would then be: java -Dkey=value -jar application.jar




回答3:


You can't use classpath wildcards in the manifest.

Take a look at Setting the classpath for more information on how classpath works:

class path wildcards are not honored in the Class-Path jar-manifest header.




回答4:


Yes, and for the shell, ~ means $HOME, but for java, it doesn't mean anything.




回答5:


The problem was that I also had an index file. If you have an index file, the Class-Path will be ignored.



来源:https://stackoverflow.com/questions/6109625/specifying-classpath-for-a-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!