原本代码如下
第一步:获取文件路径
public static String getXmlPath(String type) throws FileNotFoundException, UnknownHostException {
// 从项目中获取打包config的demo
File path = new File(ResourceUtils.getURL("classpath:").getPath());
String absolutePath = path.getAbsolutePath();
System.out.println(absolutePath);
if (!path.exists())
path = new File("");
System.out.println("path:" + path.getAbsolutePath());
String pathforpackage = "src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "configdemo" + File.separator + "configforpackagedevelop.xml";
String oldPath = "target" + File.separator + "classes";
if (type == "packagedev") {
String packagepath = absolutePath.replace(oldPath, pathforpackage);
return packagepath;
}
return "";
}
第二部:根据文件路径读取文件数据
// Java读取本地文件
public static String getLocalXmlfileFile(String path) {
File file = new File(path);
StringBuilder localStrBulider = new StringBuilder();
if (file.isFile() && file.exists()) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");// gbk
BufferedReader bufferReader = new BufferedReader(inputStreamReader);
String lineStr = null;
try {
while ((lineStr = bufferReader.readLine()) != null) {
localStrBulider.append(lineStr + "\r\n");
}
bufferReader.close();
inputStreamReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("file read error!");
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("file catch unsupported encoding!");
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("file not found!");
e.printStackTrace();
}
} else {
System.out.println("file is not a file or file is not existing!");
}
System.out.println("localStrBulider.toString():" + localStrBulider.toString());
return localStrBulider.toString();
}
修改后如下
public static String getXml(String type) {
//springboot 中打jar后读取文件,必须用以下方法读取,不然识别不到
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("classpath:configdemo");
stringBuilder.append(File.separator);
if (type == "packagedev") {
stringBuilder.append("configforpackagedevelop.xml");
}
String path = stringBuilder.toString();
Resource fileRource = new ClassPathResource(path);
InputStream inputStream = null;
try {
inputStream = fileRource.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String result = com.shishike.susie.utility.FileUtil.InputStream2String(inputStream);
return result;
}
文件路径如下:
本文介绍了一种在Spring Boot环境中优化文件读取的方法,通过使用ClassPathResource替代传统的文件路径匹配方式,有效解决了打包后的资源文件无法被正确读取的问题。
3296

被折叠的 条评论
为什么被折叠?



