摘要:通过Spring工具类获取classpath下的文件资源;获取jar包中的资源文件
1. web项目下classpath文件获取
方法(1)File resourcefile = ResourceUtils.getFile("classpath:application.properties");
方法(2) Resource resourcefile = new ClassPathResource("application.properties");
获取文件:resourcefile .getFile() / 获取文件流:resourcefile .getInputStream();
2. 获取web项目jar包中文件:
方法(1) :Resource fileRource = new ClassPathResource("application.properties");
获取文件流:fileRource.getInputStream();
方法(2) :Thread.currentThread().classLoader().getResourceAsstream()
private String readFileByLines(String filePath) throws Exception {
StringBuffer str = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(findClassLoader().getResourceAsStream(filePath)
, "UTF-8"));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
str = str.append(" " + tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return str.toString();
}
/**
* 配合api读取linux环境下jar包中的文件路径
* @return
*/
private ClassLoader findClassLoader(){
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if(loader==null){
loader = ClassLoader.getSystemClassLoader();
}
return loader;
}Class.getResource("")获取的是相对于当前类的相对路径
Class.getResource("/")获取的是classpath的根路径
ClassLoader.getResource("")获取的是classpath的根路径
springboot 项目:
配置文件读取:
(1)方式 一: 可以通过 置顶文件的位置
resources:
static-locations: file:c:/files/,classpath:/document/,classpath:/static/(2)方式二: maven 编译
<build>
<finalName>shanhero-order</finalName>
<resources>
<resource>
<directory>lib</directory>
<targetPath>/BOOT-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xlsx</include>
</includes>
</resource>
</resources>
</build>版权声明:本文为weixin_42247563原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。