Class.getResource()与Class.getResourceAsStream()方法获取文件

来源:互联网 发布:波司登保暖内衣知乎 编辑:程序博客网 时间:2024/06/06 08:43
如有以下目录
|--project
    |--src
        |--javaapplication
            |--Test.java
            |--file1.txt
        |--file2.txt
    |--build 
        |--javaapplication
            |--Test.class
            |--file3.txt
        |--file4.txt


在上面的目录中,有一个src目录,这是JAVA源文件的目录,有一个build目录,这是JAVA编译后文件(.class文件等)的存放目录
那么,在Test类中如何获得“file1.txt”,“file2.txt”,“file3.txt”,“file4.txt”这四个文件?
file3.txt:
方法一:File file3 = new File(Test.class.getResource("file3.txt").getFile());
方法二:File file3 = new File(Test.class.getResource("/javaapplication/file3.txt").getFile());
方法三:File file3 = new File(Test.class.getClassLoader().getResource("javaapplication/file3.txt").getFile());


file4.txt:
方法一:File file4 = new File(Test.class.getResource("/file4.txt").getFile());
方法二:File file4 = new File(Test.class.getClassLoader().getResource("file4.txt").getFile());
以上均可。


但是"file1"与"file2"如何获得?
只能写上它们的绝对路径,不能像file3与file4一样用class.getResource()这种方法获得,它们的获取方法如下
假如整个project目录放在c:/下,那么file1与file2的获取方法分别为
file1.txt
方法一:File file1 = new File("c:/project/src/javaapplication/file1.txt");


file2.txt
方法一:File file2 = new File("c:/project/src/file2.txt");


总结,想获得的文件,须从最终生成的.class文件为着手点,而不是以.java文件的路径为出发点,因为真正使用的是.class,而不是.java文件。
至于getResouce()方法的参数,以class为出发点,再结合相对路径的概念,就可以准确地定位资源文件了。
其根目录根据不同的IDE编译出来是不同的位置。不过都是以顶层package作为根目录。
比如在JAVA Web工程中,有一个WEB-INF的目录,WEB-INF目录下有一个classes目录。
此即为WEB工程的package的顶层目录,也是所有.class的根目录“/”。
假如clasaes目录下面有一个“file.txt”文件,它的相对路径就是"/file.txt"。如果相对路径不是以"/"开头,则是相对于当前.class文件的路径。
getResourceAsStream()方法:参数与getResouce()方法一样,相当于用getResource()取得File文件后,再用new InputStream(file)封装的结果。