關于讀取資源文件(如文本文件、圖像、二進制文件等),一般不推薦直接給出操作系統的路徑,而是給出相對于當前類的相對路徑,這樣就可以使用類的裝載器來裝載資源文件。常用的方法有:
Class類的getResourceAsStream(String resourcePath);
ClassLoader類的getResourceAsStream(String resourcePath)
Class類的該方法最終還是委派給ClassLoader的getResourceAsStream方法,但是使用中發現Class#getResourceAsStream()使用的是絕對路徑(以/開頭),而ClassLoader#getResourceAsStream()使用的相對路徑。
propterty文件經常放在類路徑的根路徑下(最頂層包的上層目錄,如classes),這樣加載property文件時就可以先用Class#getResourceAsStream方法獲取輸入源,再從該輸入源load各entry。
code piece:
package sinpo.usagedemo;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import junit.framework.TestCase;
/**
* @author 徐辛波(sinpo.xu@hotmail.com)
* Oct 19, 2008
*/
public class LoadResource extends TestCase {
public void test() throws Exception {
//usage 1: use absolute path (mostly used)
InputStream in1 = this.getClass().getResourceAsStream("/sinpo/test2.properties");
//usage 2: use relative path
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream("sinpo/test2.properties");
//usage 3: use system class path
InputStream in3 = ClassLoader.getSystemResourceAsStream("system.properties");
//將讀取的資源作為Properties的輸入源
Properties props = new Properties();
props.load(in1);
String propValue = props.getProperty("propKey");
System.out.println(propValue);
//將讀取的資源作為文本輸出
InputStreamReader reader = new InputStreamReader(in1);
BufferedReader bReader = new BufferedReader(reader);
String content = bReader.readLine();
//輸出第一行內容
System.out.println(content);
//TODO close them
}
} |