getResource()与decode()

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。

  1. 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路径的问题整理的不错,忘得时候记得看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值