在设计项目时候,使用json文件来进行接口模板匹配使用。但是在使用开发过程中,用的好好的,并且能够进行配置文件读取,遍历文件夹,但是后期问题就出现了。在 要测试使用时候,打成jar包以后。就不能使用了。最后改变设计方式。直接通过InputStream来进行针对性解析文件。
这些方案还是通过网上资料查询汇总的。如果有谁有更好的方式麻烦留言。我想做到的是资源文件初始化就能够文件夹遍历循环读取资源文件,不需要针对性的开发模板才开始读取文件。
前提摘要:
为了能够读取resourse资源文件下自定义文件夹,则需要提前配置maven,否则默认仅加载读取resource下的文件,不能读取自定义文件夹中的文件。
资源文件结构目录 :
maven特殊配置:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.json</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.json</include>
<include>**/*.yml</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
</resources>
</build>
这样就可以 读取资源 文件,自定义读取文件类型。
读取方式:
json:
ClassPathResource classPathResource = new ClassPathResource(fileConnectPath);
try{
InputStream inputStream = classPathResource.getInputStream();
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bfReader = new BufferedReader(reader);
String tmpContent = null;
while ((tmpContent = bfReader.readLine()) != null) {
builder.append(tmpContent);
}
String jaon = builder.toString();//读取到文件字符串
} catch (IOException e) {
e.printStackTrace();
log.error("The " + fileName + " file not exist in config/" + filePath + " path" + e);
} finally {
inputStream.close();
bfReader.close();
}
读取properties更方便:
Properties propertiesFile = new Properties();
propertiesFile.load(inputStream); //inoutstream存放位置
propertiesFile.getProperty(“配置文件中key值”);
然后可以本地打jar包读取尝试。