2013-02-22 10:19 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", " ");



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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());
                 }
             }
         }
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值