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());
}
}
}
}
}
|