URLDecoder.decode

前几天学习的时候遇到一个问题,Exception in thread “main” java.io.FileNotFoundException: path1 (系统找不到指定的文件。)。当时纠结了很久没有找到原因。后来通过一步步调试代码终于找到原因了。
通过类加载器获取一个工程目录中的一个文件的路径即通过方法class.getClassLoader().getResource(fileName)获取的路径时,如果该路径名有空格则获得的路径名是经过url编码后的路径。这时如果使用FileInputStream fin = new FileInputStream(“path1”);则会报错:Exception in thread “main” java.io.FileNotFoundException: path1 (系统找不到指定的文件。)。
解决办法:将class.getClassLoader().getResource(fileName)获取的路径名进行URL解码,String path2 = URLDecoder.decode(url.getPath(),”gbk”)。
Demo如下:

public class test {
    public static void main(String[] args) throws DocumentException, IOException {
        URL url = test.class.getClassLoader().getResource("1.xml");

        //url解码
        String path1 = URLDecoder.decode(url.getPath(),"gbk");
        System.out.println(path1);
        FileInputStream fin1 = new FileInputStream(path1);

        String path2 = url.getPath();
        System.out.println(path2);
        FileInputStream fin2 = new FileInputStream(path2);

    }
}

/D:/Users/LBX/Workspaces/MyEclipse 2015 CI/PageLogin/WebRoot/WEB-INF/classes/1.xml
/D:/Users/LBX/Workspaces/MyEclipse%202015%20CI/PageLogin/WebRoot/WEB-INF/classes/1.xml
Exception in thread "main" java.io.FileNotFoundException: D:\Users\LBX\Workspaces\MyEclipse%202015%20CI\PageLogin\WebRoot\WEB-INF\classes\1.xml (系统找不到指定的路径。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at cn.liu.test.test.main(test.java:29)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值