URLDecoder.decode

来源:互联网 发布:淘宝gta5刷钱靠谱吗 编辑:程序博客网 时间:2024/06/05 06:39

前几天学习的时候遇到一个问题,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.xmlException 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)
0 0