windows环境和linux环境下获取文件路径名并读取文件内容
在编写代码时我们经常会发生明明测试环境没问题,但是到线上生产环境中就出bug,这是因为我们常常在本地环境与线上环境文件存放的路径不一致,这里我们直接获取Resource下资源文件windows的与linux的文件分隔符"\"是不一样的这样会导致文件路径不存在的错误产生我们要用 File.separator替代
{
String filePath = this.getClass().getResource("/").getPath() + "file" + File.separator + "json";
//获得target下的资源文件
File file = ResourceUtils.getFile(filePath);
List<String> fileNames = new ArrayList<>();
File[] files = file.listFiles();
这段代码在springboot打包成jar包后无法根据File访问jar包里面的路径修改成以下:
}
List<String> fileNames = new ArrayList<>();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:file/json".concat("/*"));
for (Resource resource : resources) {
fileNames.add(resource.getFilename());
}
if(files.length>0){
Arrays.stream(files).forEach(fileName -> {
fileNames.add(fileName.getName());
});
if (fileNames.size() > 0) {
// 解析文件数据
for (String fileName : fileNames) {
//拿到文件名后,ClassPathResource 拼写文件所在的Resource路径名
String filePathRelative= "file" + File.separator + "json" + File.separator + fileName;
//用classPathResource获取文件并以流的方式读取出来写入字节流
ClassPathResource classPathResource = new ClassPathResource(filePathRelative);
InputStream inputStream = classPathResource.getInputStream();
ByteArrayOutputStream result = new ByteArrayOutputStream();
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
//将字节流转换成json文件
JSONObject jsonObject = JSONObject.parseObject(result.toString(StandardCharsets.UTF_8.name()));
}
}
}