java jar包 配置文件_java 导入jar包中配置文件
spring項目只能識別到項目內的xml配置文件,無法識別jar中xml配置文件
解決思路:
在啟動初始化期間,將jar包內部的文件拷貝到jar包外部相對路徑中。//jarFullFileName:?the?file?name?with?full?path?in?jar.
//newFilePath:?the?new?file?directory.?"./"?means?the?current?directory?of?jar?file.
public?boolean?newFileFromJar(String?jarFullFileName,?String?newFilePath){
String[]?jarFilePath?=?null;
String?newFileName?=?null;
File?file?=?null;
OutputStream?os?=?null;
InputStream?is?=?null;
try?{
//check?if?the?source?file?existed.
is?=?Configer.class.getResourceAsStream(jarFullFileName);
if(is?==?null){
System.out.println("Fail?to?get?input?stream.");
return?false;
}
//get?the?new?file's?full?path?name
jarFilePath?=?jarFullFileName.split("/");
newFileName?=?newFilePath+jarFilePath[jarFilePath.length-1];
System.out.println(newFileName);
//open?or?create?the?new?file
file?=?new?File(newFileName);
if(file.exists()){
System.out.println("file?existed.");
}
else?{
if(file.createNewFile()?==?false)?{
System.out.println("fail?to?create?new?file?"+newFileName);
return?false;
}
}
os?=?new?FileOutputStream(file);
//copy?file?content
byte[]?buff?=?new?byte[1024];
while?(true)?{
int?readed?=?is.read(buff);
if?(readed?==?-1)?{
break;
}
byte[]?temp?=?new?byte[readed];
System.arraycopy(buff,?0,?temp,?0,?readed);
os.write(temp);
}
}
catch(Exception?e)?{
e.printStackTrace();
return?false;
}
//close?the?io?streams
try?{
if(os?!=?null)
os.close();
if(os?!=?null)
os.close();
}?catch?(IOException?e1)?{
e1.printStackTrace();
}
return?true;
}
...
//注意:參數jarFullFileName是jar包內部的相對路徑,如路徑"/applicationContext.xml"表示jar包根目錄下的文件
newFileFromJar("applicationContext.xml",".");//copy?the?file?to?the?current?directory?of?jar?file
注意:
在使用獨立jar文件運行的java代碼中,沒法使用ClassPathXmlApplicationContext(..)來加載Spring的配置文件,因為該方法只能用于讀取WEB-INF\classes下的配置文件。此時需要使用FileSystemXmlApplicationContext(..)方法來加載配置文件。
---------------------
參考:
https://blog.csdn.net/shandian534/article/details/37762301
https://blog.csdn.net/zxygww/article/details/48522873
總結
以上是生活随笔為你收集整理的java jar包 配置文件_java 导入jar包中配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringMVC配置静态资源加载, 中
- 下一篇: python fillna,Pandas