读取外部jar文件的属性文件

时间:2017-05-10 23:33:23

标签: java dependencies classpath executable-jar

我使用eclipse创建了一个Runnable .jar文件,其中包含一个带有main方法的类。当你从java -jar myjar.jar命令行运行jar时,所有它都是从.properties文件读取属性并创建类com.vehicles.BMW的实例,所以说我们有一个文件(在某个地方)类路径IT必须在名为car.properties的类路径中,文件格式如下:

car.className=com.vehicles.BMW
car.make=bmw
car.model=320i

所以我的主要代码如下(假设我们有一个Interface Car):

  public static void main(String[] args)throws IOException{
       Properties p = loadFileProperties( );
       String className = p.getProperty("car.className");
       Car car = (Car)Class.forName(className).newInstance(); //assume i handled the checked Exceptions on this line.
       //we'll just print these out
       sysout.....statement (p.getProperty("car.make"));
       sysout.....statement (p.getProperty("car.model"));
  }

  public static Properties loadFileProperties( ) throws IOException {
    //look for the file somewhere in the classpath.
    InputStream inputStream = MyWorkEngine.class.getClassLoader( ).getResourceAsStream( "car.properties" );
    Properties properties = new Properties( );
    properties.load( inputStream );
    properties.close();
    return properties;
  }

该文件必须位于运行jar时指定的类路径中。当我在类路径中拥有自己的car.properties文件时,这个代码当然可以正常工作,即(如果它包含在jar中)但我希望能够将.jar文件提供给其他人它必须能够从命令行在他们的机器上运行它时读取它们.properties文件,并通过-cp告诉它在哪里查找它需要的任何依赖项或任何资源(包括属性文件)

它必须阅读它并创建一个实例Car实现,比如说com.vehicles.MercedesBenz并做与我的相同的事情。该人的文件也将被命名为car.properties

我希望能够将我的罐子交给很多人,他们应该将它指向他们的类路径并且必须运行。如何在命令行中实现这一目标?

我在另一个类似的问题中看到过这样的问题java -cp myjar.jar:lib/* ClassThatHasMain,我试过了,我失败了,不明白。所以我决定问自己的问题。

0 个答案:

没有答案
相关问题