Web Development 的學習之旅

2008/06/04

Load resource file test / 讀取資源檔案測試

測試 function:
object.getClass().getResourceAsStream(filename);

Project 的資料夾結構:



結論:
* 只寫檔名只能找到與該 class 相同的 namespace 下的檔案.
* 若以相對路徑的寫法, 則 jar 檔內的檔案一律找不到. 即使在相同目錄也找不到.
* 以絕對路徑的寫法, 可以完全找到.


Project: ResTest1


package tw.purple.test;

import java.io.*;

public class ResTest1 {
public static void main(String[] args) {
ResTest1 test = new ResTest1();
test.runTest();
}

public void runTest() {
String[] pathList = {
""
,"./"
,"/"
,"../"
,"../../"
,"../../../"
,"/tw/"
,"/tw/purple/"
,"/tw/purple/test/"
,"/tw/yahoo/"
};
String[] nameList = {
"log4j_1.properties"
,"log4j_2.properties"
,"log4j_3.properties"
,"log4j_4.properties"
,"log4j_5.properties"
,"log4j_6.properties"
,"log4j_7.properties"
,"log4j_8.properties"
};

for (int i=0; i<pathList.length; i++) {
for (int j=0; j<nameList.length; j++) {
String filename = pathList[i] + nameList[j];
InputStream stream = this.getClass().getResourceAsStream(filename);
if (stream==null) System.out.print(" not found: ");
else System.out.print(" found: ");
System.out.println(filename);
}
}
}

}



Project: ResTest2

package tw.purple.test;

public class ResTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ResTest1 test1 = new ResTest1();
test1.runTest();
}
}