2016-11-5

Java

资源加载

文件资源加载

加载方式​​路径规则​
Class.getResourceAsStream(path)
// 可直接读取jar资源文件 /testB.txt/ 表示classpath, 不加当前类的编译路径
InputStream inputStream = App.class.getResourceAsStream(“/testB.txt”)
• 以 /开头:从 ​​classpath 根目录​​查找
• 不以 /开头:从 ​​当前类所在包目录​​查找
//通过类加载器​
ClassLoader.getResourceAsStream(name)
• ​​必须从 classpath 根目录开始​
• ​
​不能​​以/开头 !
Class.getResource(path)
//获得类编译输出的目录
Class.class.getResource("/").getPath()
同 Class.getResourceAsStream
ClassLoader.getResource(name)同 ClassLoader.getResourceAsStream
Files.newInputStream(Path)基于​​文件系统路径​​(绝对或相对工作目录)
ClassLoader.getSystemResourceAsStream(name)同 ClassLoader.getResourceAsStream
System.getProperty("user.dir");返回当前程序工作目录
System.getProperty("user.home");ObjectOutputStream返回用户目录

本地库加载(JNI)

System.load

System.load 参数必须为库文件的绝对路径, 可以是任意路径, 例如:

System.load("C:\\Documents and Settings\\TestJNI.dll"); //Windows
System.load("/usr/lib/TestJNI.so"); //Linux

注意:

  1. 必须传入库文件的​​完整绝对路径​​(包括文件名和扩展名)
  2. 不会​​像 loadLibrary()那样自动添加 lib前缀或 .so/.dll后缀
  3. 必须​​显式包含文件名和扩展名​​(如 libmylib.so或 mylib.dll)

System.loadLibrary

System.loadLibrary 参数为库文件名, 不包含库文件的扩展名;

System.loadLibrary ("TestJNI"); //加载Windows下的TestJNI.dll本地库
System.loadLibrary ("TestJNI"); //加载Linux下的libTestJNI.so本地库

注意:

 -Djava.library.path=build/libs

TestJNI.dll 或 libTestJNI.so 必须是在JVM属性 java.library.path 所指向的路径中; 如果 java.library.path未设置或未找到库,JVM 会查找​​平台相关的默认路径​​。

  • ​Linux/Unix:​​ 通常包括 /usr/lib/usr/local/lib,以及 LD_LIBRARY_PATH环境变量指定的路径。
  • ​macOS:​​ 通常包括 /Library/usr/lib,以及 DYLD_LIBRARY_PATH环境变量指定的路径
  • ​Windows:​​ 通常包括:
    • 当前工作目录 (JVM 启动时的目录)。
    • PATH环境变量列出的目录。
    • System32目录 (e.g., C:\Windows\System32)。