Tomcat下獲取當前類的路徑中含有空格的解決方案
阿新 • • 發佈:2019-01-31
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());
}
}
}
}
}
|