浅析java.lang.Class的getResource()的使用

该方法通过利用类装载器(CLassLodaer),查找特定名称的资源文件。
查找的起点是编译后的类文件的根目录,以WEB工程为例来说,如果传送的参数首字符为"/",查找的根路径(/)是WEB-INF下的class目录;如果参数的首字符不为"/",查找的起点则为调用类所在目录,即通过与该类文件的相对路径查找资源文件。

示例如下:
比如我们有以下目录

|--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与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");

方法二:。。。也没有
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值