在J2SE中,或者不發佈的webapp下測試:html
File file=new File("./text.xml") 發現讀取src下面的text.xml文件java
可是當咱們把webapp發不到tomcat下面,你會發現他找不到路徑了,他會到tomcat bin文件下面去找。web
其實webapp發佈的時候,會把源文件的class放到WEB-INF/classses下面,會把工程中WEB-INF下面的東西放到發佈的WEB-INF下面,如jsp,lib等等。tomcat
因此程序要讀取配置文件,好比我偶們把配置文件放到conf下面,發現發佈後,WEB-INF/classses沒有這個配置文件,緣由是這個conf文件只是普通文件夾,必需要和src同樣是源文件夾才行。因此配置文件有三种放的方法:app
1 直接放到src下面
webapp
2 創建源的文件夾,如conf,放到下面,其實最後編譯都會放到WEB-INF/classses下面,這樣放只是爲了和普通的src區分jsp
3 放到工程WEB-INF目錄下面測試
好比我在src下面放了一個mapping.xml,讀取他這樣;好比這段帶嗎在Test類裏面
spa
String path=Test.class
.net.getClassLoader().getResource(
"mapping.xml"
).getPath();
File file=new File(path);
這樣就搞定了。
這是別人的代碼:
package
org.cheng.file;
import
java.io.File;
public
class
FileTest{
public
static
void
main(String[]args)
throws
Exception{
System.out.println(Thread.currentThread().getContextClassLoader().getResource(
""
));
System.out.println(FileTest.
class
.getClassLoader().getResource(
""
));
System.out.println(ClassLoader.getSystemResource(
""
));
System.out.println(FileTest.
class
.getResource(
""
));
System.out.println(FileTest.
class
.getResource(
"/"
));
//Class文件所在路徑
System.out.println(newFile(
"/"
).getAbsolutePath());
System.out.println(System.getProperty(
"user.dir"
));
}
}
參考博客,這兩個頗有用,感謝他們:
http://my.oschina.net/xianggao/blog/85172#OSC_h4_8
http://www.bubuko.com/infodetail-776607.html