Java 读取jar文件外部的属性文件
我已经使用eclipse创建了一个可运行的Java 读取jar文件外部的属性文件,java,dependencies,classpath,executable-jar,Java,Dependencies,Classpath,Executable Jar,我已经使用eclipse创建了一个可运行的.jar文件,其中有一个类包含main方法。当您使用java-jar myjar.jar从命令行运行jar时,它所做的只是从.properties文件中读取属性,并创建类com.vehicles.BMW的实例,因此假设我们有一个名为car.properties的文件(在类路径的某个地方,它必须在类路径中),文件格式如下所示: car.className=com.vehicles.BMW car.make=bmw car.model=320i 因此,我的
.jar
文件,其中有一个类包含main
方法。当您使用java-jar myjar.jar
从命令行运行jar时,它所做的只是从.properties
文件中读取属性,并创建类com.vehicles.BMW
的实例,因此假设我们有一个名为car.properties
的文件(在类路径的某个地方,它必须在类路径中),文件格式如下所示:
car.className=com.vehicles.BMW
car.make=bmw
car.model=320i
因此,我的main中的代码如下所示(假设我们有一个接口
汽车):
文件必须位于运行jar时指定的类路径中。当我在类路径中有自己的car.properties
文件时,这段代码当然可以正常工作,也就是说(如果它包含在jar中的话)但是我希望能够将.jar
文件提供给其他人,并且当他们从命令行在机器上运行.properties
文件时,它必须能够读取他们的.properties
文件,并通过-cp
告诉它在哪里查找它需要的任何依赖项或任何资源(包括属性文件)
它必须读取它并创建一个实例,比如说com.vehicles.MercedesBenz
,然后像处理我的一样处理它们的Car
实现。此人的文件也将命名为car.properties
我希望能够将我的jar提供给很多人,他们应该将它指向他们的类路径,并且它必须运行。如何在命令行中实现这一点
我在另一个类似的问题中看到过,类似于java-cp myjar.jar:lib/*类的东西,它有main,我尝试过,但失败了,不理解。所以我决定问我自己的问题。你为什么不自己制作一个类加载器呢?apache的ant launcher项目将是一个很好的起点。为什么不制作自己的类加载器呢?apache的ant launcher项目将是一个很好的起点。
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;
}