Fork me on GitHub

Tomcat下获取当前类的路径中含有空格的解决方案

web项目发布到Tomcat之后,如果tomcat是安装在比如

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\****

那么你获取当前类的路径的时候,就会出现问题,因为它会报出%20

C:\Program%20Files\Apache%20Software%20Foundation\Tomcat 6.0\webapps\****


这个时候你再做一些关于文件的操作,程序就挂了,报一些未知错误,那么解决方案就是使用字符串的replace方法,进行字符串替换即可.

 

//获取当前类加载器,并找到指定目录POOLCONFIG_FOLDER是之前设置好的static 变量

String path = Thread.currentThread().getContextClassLoader().getResource(POOLCONFIG_FOLDER).getPath();

//进行字符串替换

path = path.replace("%20", " ");



public class DBUtil{         private static String POOLCONFIG_FOLDER = "pools";         private static void init()    {        /**         * 方法一,利用当前类加载器1         */        // URL url = Thread.currentThread().getContextClassLoader().getResource(POOLCONFIG_FOLDER);        // String path = url.getFile();        // path = path.replace("%20", " ");        //  File folder = new File(path);                 /**         * 方法二,利用当前类加载器2         */        //String path = DBUtil.class.getClassLoader().getResource(POOLCONFIG_FOLDER).getPath();        //path = path.replace("%20", " ");        // File folder = new File(path);                          /**         * 方法三,利用当前线程类加载器         */        String path = Thread.currentThread().getContextClassLoader().getResource(POOLCONFIG_FOLDER).getPath();        path = path.replace("%20", " ");        File folder = new File(path);        logger.debug("path :" + path);        if (folder.isDirectory())        {            File[]fileList = folder.listFiles();            for (int i = 0, len = fileList.length; i < len; i++)            {                try                {                    File file = fileList[i];                    String name = file.getName();                    name = name.substring(0, name.lastIndexOf("."));                    InputStream input = new FileInputStream(file);                    Properties props = new Properties();                    props.load(input);                    loadPoolConfig(name, props);                }                catch (Exception e)                {                    e.printStackTrace();                    logger.info("加载DBUtil出现问题。。。。。");                    logger.error(e.getMessage());                }            }        }    }}


posted @ 2013-02-22 10:19  _落雨  阅读(495)  评论(0编辑  收藏  举报