加载资源文件路径:
db.properties
注意:加载properties文件,只能使用Properties类的load方法.
——————————————
方式1:使用绝对路径的方式加载.该方式不可行.
1 2 3 4 5 6 7 | //方式1:使用绝对路径的方式加载. 该方式不可行. private static void test1() throws Exception { Properties p = new Properties(); InputStream inStream = new FileInputStream("C:/Users/Lin/Desktop/Project/08反射机制/resource/db.properties"); p.load(inStream);//加载 System.out.println(p); } |
方式2:使用相对路径–相对于classpath的根路径(字节码输出目录).
此时得使用ClassLoader(类加载器),类加载器默认就是从classpath根路径去寻找文件的.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //方式2:使用相对路径-相对于classpath的根路径(字节码输出目录). //ClassLoader(类加载器),类加载器默认就是从classpath根路径去寻找文件的. private static void test2() throws Exception { Properties p = new Properties(); //两种获取类加载器的方法 //ClassLoader loader = LoadResourceDemo.class.getClassLoader(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream inStream =loader.getResourceAsStream("db.properties"); p.load(inStream);//加载 System.out.println(p); } |
方式3:使用相对路径–相对于当前加载资源文件的字节码路径
1 2 3 4 5 6 7 8 9 | //方式3:使用相对路径-相对于当前加载资源文件的字节码路径 //bin/com/_520it/_06_load_resource路径去寻找. private static void test3() throws Exception { Properties p = new Properties(); InputStream inStream =LoadResourceDemo.class.getResourceAsStream("db.properties"); p.load(inStream);//加载 System.out.println(p); } |
在这里使用的是LoadResourceDemo的字节码路径去寻找db.properties文件.
也就是从bin/com/_520i/_06_load_resource路径去寻找.
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
个人编程学习网
本文地址: Java-加载资源文件路径
本文地址: Java-加载资源文件路径
您必须 登录 才能发表评论