贴上一个工具类给以后参考
package com.bosssoft.hr.jobmonitor.core.file;
import com.bosssoft.hr.jobmonitor.config.common.SysConfig;
import com.bosssoft.hr.jobmonitor.util.DateUtil;
import com.bosssoft.hr.jobmonitor.util.XmlUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import java.io.*;
import java.net.URLDecoder;
import java.util.Date;
public class FileTool {
/** 读取文件信息
* @param filename 文件名称
* @return 资源文件内容
*/
public String readFile(String filename){
BufferedReader br=null;
StringBuilder stringBuilder=new StringBuilder();
InputStream in=null;
Resource resource =new ClassPathResource(filename);
try {
in = resource.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
try {
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
}catch (Exception e){
e.printStackTrace();;
}
return stringBuilder.toString();
}
/**
* 将字符串写入文件中
* @param filename 文件名称(含路径)
* @param xmlStr 字符串
*/
public void writeFile(String filename,String xmlStr){
OutputStream outputStream=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
// ClassPathResource resource =new ClassPathResource(filename);
String basePatha1 = ClassUtils.getDefaultClassLoader().getResource(filename).getPath();
try {
basePatha1 = URLDecoder.decode(basePatha1, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
outputStream = new FileOutputStream(basePatha1);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw = new OutputStreamWriter(outputStream);
bw = new BufferedWriter(osw);
bw.write(xmlStr);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bw.close();
osw.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取系统通用配置
* @return 获取系统
*/
public SysConfig getSysConfig(){
String xmlStr = readFile("resource"+File.separator+"common"+File.separator+"sysConfig.xml");
SysConfig sysConfig = XmlUtil.toBean(xmlStr, SysConfig.class);
return sysConfig;
}
public void updateSysConfig(){
SysConfig sysConfig = getSysConfig();
String newXmlStr = XmlUtil.toXml(sysConfig);
writeFile( "resource"+File.separator+"common"+File.separator+"sysConfig.xml",newXmlStr);
}
/**
* 在作业目录创建作业日期文件夹
*/
public void makeHomeworkDir() {
String todayDir = DateUtil.getTodayDir(new Date());
SysConfig sysconfig = getSysConfig();
File file = new File(sysconfig.getHomeDir() + File.separator + todayDir);
file.mkdirs();
}
}
测试可以访问打包成jar后的springboot项目的资源文件。