该方法通过利用类装载器(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");
方法二:。。。也没有
分享到:
相关推荐
- **基于接口的动态代理**:使用 `java.lang.reflect.Proxy` 类和 `java.lang.reflect.InvocationHandler` 接口来实现。 - **基于类的动态代理(CGLIB)**:使用第三方库 CGLIB 来实现代理,适用于无法使用基于接口...
在实际编程中,还应该考虑使用`java.time`包提供的`LocalDate`, `LocalTime`和`LocalDateTime`等类,它们提供了更强大、更易用的日期时间处理功能。对于国际化的日期格式处理,`java.time.format.DateTimeFormatter`...
Java的并发工具主要集中在java.lang.Thread类和java.lang.Runnable接口中,它们是实现多线程的基础。 首先,我们从Thread类开始。Thread类是实现Runnable接口的一个具体类,它的run方法用于定义线程执行的操作。...
### Java中main()方法浅析 #### 一、概述 在Java编程语言中,`main()`方法具有特殊的意义,它是所有Java应用程序的起点。当Java虚拟机(JVM)启动并加载了一个包含`main()`方法的类时,它会自动调用这个方法来开始...
投票制度浅析学习.pdf
地板行业浅析报告.pptx
民事立法浅析论文.doc
在Java中,反射主要依赖于`java.lang.Class`类和`java.lang.reflect`包中的相关类和接口。 首先,Java反射机制允许我们在运行时获取类的元数据,包括类的名称、属性(字段)和方法。例如,通过`Class.forName()`...
企业大数据应用浅析35.pptx
高校外事翻译浅析论文.doc
农村居民收入浅析论文.doc
浅析JAVA代理模式.pdf
全生命周期BOM管理浅析qytp.pptx
全生命周期BOM管理浅析qy.pptx
小学数学高效课堂浅析论文.doc
创新联合担保模式浅析论文.doc
开口贝袁大头别浅析甘肃.docx
网络安全与病毒防护浅析.ppt网络安全与病毒防护浅析.ppt网络安全与病毒防护浅析.ppt