您的位置:首页 > 编程语言 > Java开发

getResource()与decode()

2015-09-26 22:10 477 查看
1.getResource()

通过利用类装载器(CLassLodaer),查找特定名称的资源文件。查找的起点是编译后的类文件的根目录,用eclipse编辑器的话是从bin开始查找,通过与该类文件的相对路径查找资源文件。如果找不到就返回null,找到了就返回路径。

package test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;

public class TestDemo {

public static void main(String[] args) throws IOException {
String filename=fileToPath("hello.txt");
System.out.println("value3="+filename);
}
public static String fileToPath(String filename) throws UnsupportedEncodingException
{
URL url=TestDemo.class.getResource(filename);
System.out.println("value1="+url);
System.out.println("value2="+url.getPath());
return java.net.URLDecoder.decode(url.getPath(), "UTF-8");
}
}


输出信息:

value1=file:/D:/EclipseWorkspace1/test/bin/test/hello.txt
value1=file:/D:/EclipseWorkspace1/test/bin/test/hello.txt
value3=/D:/EclipseWorkspace1/test/bin/test/hello.txt


由此也可以看出我的hello.txt必须放在bin目录下,否则会打印出null。

decode()(参考:http://www.cnblogs.com/shishm/articles/1614407.htmlhttp://yanguz123.iteye.com/blog/1943385

作用:将application/x-www-form-urlencoded字符串转换成普通字符串。而application/x-www-form-urlencoded字符串是一种编码类型。当URL地址里包含非西欧字符的字符串时,系统会将这些字符转换成application/x-www-form-urlencoded字符串。

ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的中文及空格路径

例如:结果是 file:/C:/Documents%20and%20Settings/%e5%ba%84%e6%99%93%e6%af%85/Local%20Settings/Temp/temp0.jar!/db/dmozdata.mdb

而我们期望是 C:/Documents 路径p source 等等。这里我们只要在获取到路径之前把返回值decode下就可以了. 用utf-8编码. Java代码 :

String configPath = this.getClass().getClassLoader().getResource(“allowPath.xml”).getFile();

configPath = java.net.URLDecoder.decode(configPath,”utf-8”);

另外java中URL 的编码和解码函数分别是java.net.URLEncoder.encode(String s)和java.net.URLDecoder.decode(String s)

http://yanguz123.iteye.com/blog/1943385这个博客整理的关于Java路径的问题整理的不错,忘得时候记得看
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java-路径