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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值