ClassLoader读取文件,springboot打jar包后读取不到
jar:file:/D:/test/test/.metadata/.plugins/org.eclipse.wst.server.core/test/test/test/WEB-INF/lib/test-0.0.1-SNAPSHOT.jar!/ca.crt
在你的项目中可能经常会使用ClassLoader.getSystemResourceAsStream等方法来读取一个文件内容,使用properties来读取。
但是当你打包后会发现你程序出现了问题,这个时候怎么办呢?
**解决**可以尝试一下以下的代码来获取文件,内容可自行修改,逻辑比较简单,就是获取相对地址然后得到文件
//s是地址+文件名 from fhadmin.cn
private File loadNewFromResources(String s) {
File file = new File( s);
try {
if (!file.exists()) {
file.createNewFile();
InputStream fileInput = SampleServerStartup.class.getClassLoader().getResourceAsStream( s);
//from fhadmin.cn
//file = File.createTempFile(s,"");
System.out.println(file.getPath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
//System.out.println("length:"+fileInput.available());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInput.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
fileInput.close();
//System.out.println(content); //from fhadmin.cn
FileOutputStream fileout = new FileOutputStream(file);
baos.writeTo(fileout);
baos.close();
fileout.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return file;
}


