java中的Class.getResource()方法

xiaoxiao2026-08-15  31

当你想要在java类包中某个层次上添加一个非java文件,像资源文件,XML配置文件

或其他格式文件的时候, Class.getResource() 是一个很有用的方法,它不是根据

绝对路径来定位某个资源(文件),而是根据相对类路径来定位资源。当我们用绝对路径

来定位java类包中某个层次的资源时,项目的部署和迁移可能会出现问题,而且跨平台

运行也会出现问题。(像 "c:/1.txt"这个文件路径 在linux里是不能被识别的)

 

下面显示了一个类层次:

 

+bin--

    +test_1--

        Test.class

        +test_2--

            hello_en.txt

    hello_zh.txt

 

注意: 资源文件必须在编译后类路径里才能通过Class.getResource() 的方式被定位 ,

而不是在源文件路径里。

 

下面是Test_1的代码用来定位和读取hello_en.txt文件

package test_1; import java.io.File; import java.io.IOException; import java.io.Reader; import java.net.URISyntaxException; import java.net.URL; import java.io.FileReader; public class Test { public static void main(String[] args) throws URISyntaxException, IOException { //根据类包根层次的相对路径来定位hello_en.txt文件 URL url = Test_1.class.getResource("/test_1/test_2/hello_en.txt"); //定位hello_en.txt的另外一种方式 //根据当前类文件Test_1.class的相对路径来定位hello_en.txt文件 //URL url = Test_1.class.getResource("test_2/hello_en.txt"); File file = new File(url.toURI()); StringBuffer buffer = new StringBuffer(); Reader reader = new FileReader(file); int ch = reader.read(); while(ch != -1){ buffer.append((char)ch); ch = reader.read(); } reader.close(); System.out.println(buffer.toString()); } }

 

运行这个类文件,输出结果如下(hello_en.txt 文件的内容为 hello !):

    hello !

 

 

定位hello_zh.txt文件的代码片段如下(当然也有两种方式):

 

URL url = Test_1.class.getResource("/hello_zh.txt");

 或者

URL url = Test_1.class.getResource("../hello_zh.txt");  

 

还有一点需要注意 ,用

 

File file = new File(url.toURI());

来获取一个File对象,最好不能用

 

File file = new File(url.getFile());

因为URL.getFile()返回的文件路径字符串自动将空格转换为了ASC2编码,如果在你的绝对文件路径中含有空格,就会无法定位到这个文件,当时在这快也确实让我迷惑了一下。

Class.getResourceAsStream() 也可以用于定位和获取资源文件,和Class.getResource差不多,不过返回的是一个InputStream对象。

 

 

 

相关资源:敏捷开发V1.0.pptx
转载请注明原文地址: https://www.6miu.com/read-5051242.html

最新回复(0)