原文:http://blog.163.com/cdf_2008/blog/static/76064778200954101651458/
讀取Properties文件和路徑問題
如:讀取jdbc.properties文件
路徑
讀取的類位於:package com.query.util;
getClass().getResourceAsStream(jdbc.properties)
則jdbc.properties描述的路徑是相對於這個類所在包的根路徑而言的,
即爲相對於文件夾util所在目錄開始,
getClass().getResourceAsStream(/jdbc.properties) 以/開始
則/jdbc.properties描述的路徑是相對於這各類當前的文件夾而言的,
即爲相對於文件夾com所在目錄開始,
讀取的方法
1。使用java.util.Properties類的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2。使用java.util.ResourceBundle類的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3。使用java.util.PropertyResourceBundle類的構造函數
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
4。使用class變量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
6。使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);
補充
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
一般常使用第五種
空格
//獲得文件路徑,並對路徑進行處理
private static String getUrl()
{
String path = configLoad.class.getResource("config.properties").toString();
path = path.replace("%20", " "); //引號中有一個半角的空格
path = path.substring(6);
return path;
}
}
那麼這裏返回了一個Properties類型的值,在這裏就可以使用getProperty()來獲得值
如:Properties pro = configLoad.getConfig();
String http = pro.getProperty("url").toString();
中文
在java jdk 的bin下找到native2ascii.exe 點擊輸入中文得到asc碼