java中获取路径中的空格处理(%20)问题

在java中获取文件路径的时候,有时候会获取到空格,但是在中文编码环境下,空格会变成“%20”从而使得路径错误,解决办法如下:

dbFilePath = URLDecoder.decode(dbFilePath,”utf-8”);

        ClassLoader cl = Dom4JUtil.class.getClassLoader();
        URL url = cl.getResource("users.xml");
        System.out.println(url);
    // file:/D:/workspace/workspace-web/day13_01_regist/WebRoot/WEB-INF/classes/users.xml
        dbFilePath = url.getPath();
        System.out.println(dbFilePath);
    // /D:/workspace/workspace-web/day13_01_regist/WebRoot/WEB-INF/classes/users.xml
        dbFilePath = dbFilePath.substring(1);
        System.out.println(dbFilePath);
    // D:/workspace/workspace-web/day13_01_regist/WebRoot/WEB-INF/classes/users.xml

        public static Document getDocument() throws Exception{
        SAXReader reader = new SAXReader();
        return reader.read(dbFilePath);
        }
        public static void write2xml(Document document) throws Exception{
        //OutputStream out = new FileOutputStream("users.xml");
        System.out.println(dbFilePath);
    // D:/Program%20Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
        try {
            dbFilePath = URLDecoder.decode(dbFilePath,"utf-8"); //这步是很关键的
            System.out.println(dbFilePath);
    //D:/Program Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream out = new FileOutputStream(dbFilePath);
        XMLWriter writer = new XMLWriter(out);
        writer.write(document);
        writer.close();
    }
}

这几种路径:
file:/D:/Program%20Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
/D:/Program%20Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
D:/Program%20Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
D:/Program%20Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml
D:/Program Files/apache-tomcat-7.0.67-windows-x64/apache-tomcat-7.0.67/webapps/day13_01_regist/WEB-INF/classes/users.xml

你可能感兴趣的:(java中获取路径中的空格处理(%20)问题)