使用maven
,我正在构建一个必须动态加载驱动程序的应用程序。对于以下代码,仅当 driver.so
位于生成的 JAR 文件内部时,它才有效。我该怎么做才能在路径 ./natives/driver.so
内的 JAR外部找到该文件。
package com.myproject;
public class Starter {
public static void main(String[] args) {
File classpathRoot = new File(Starter.class.getClassLoader().getResource("driver.so").getPath());
System.out.println(classpathRoot);
}
}
驱动程序位于内部 JAR 时的输出为:
jar:file:/home/ted/java/myproject/target/myproject-0.1-SNAPSHOT.jar!/libgdx64.so
位于外部JAR(在target
以及target/natives
目录中)时的输出是:
null
我通过以下方式启动应用程序:
cd /home/ted/java/myproject/target/
java -Djava.library.path=./natives -cp myproject-0.1-SNAPSHOT.jar com.myproject.Starter
我能做什么?
最佳答案
试试这个:
package com.myproject;
public class Starter {
public static void main(String[] args) {
File file = new File("natives/driver.so");
System.out.println(file);
}
}
或者这个:
package com.myproject;
public class Starter {
public static void main(String[] args) {
File file = new File(System.getProperty("java.library.path"), "driver.so");
System.out.println(file);
}
}
关于java - 从 JAR 文件外部加载资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152252/