Class.getResource()怎么使用

来源:互联网 发布:caffe怎么用两个gpu 编辑:程序博客网 时间:2024/04/27 18:47

URL url=Class.forName("game3.PicPanel").getResource("0.JPEG");

 

Class.forName( String className )返回与带有给定字符串名的类或接口相关联的Class对象。

Class.getResource()方法的具体形式为:public URL getResource( String name )

但是这个方法在使用时,还是困扰了我很久,不知道将图片0.JPEG放在什么位置,或者说怎么样传参数给此方法,在网上查找相关资料才弄明白了。

比如我们有以下目录:

|--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.txtfile4.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());

对于file3.txtfile4.txt,我们可以有多种方法选择,但是file1file2文件呢?如何获得?

答案是,我们只能写上它们的绝对路径,不能像file3file4一样用class.getResource()这种方法获得,它们的获取方法如下

假如整个project目录放在c:/下,那么file1file2的获取方法分别为

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文件就使用,因为java是编译型语言。至于getResouce()方法的参数,你以class为出发点,再结合相对路径的概念,就可以准确地定位资源文件了.

 所以当我们想要使用getResource()方法时,就只好把文件放在.class文件相同目录下或者它的父目录中了。

原创粉丝点击