Obtain the file path name and read the file content in the windows environment and linux environment

Obtain the file path name and read the file content in the windows environment and linux environment

When writing code, we often have problems in the test environment, but bugs occur in the online production environment. This is because we often have inconsistent storage paths between the local environment and the online environment. Here we directly obtain the resources under Resource The file separator "\" of windows and linux is different, which will cause an error that the file path does not exist. We need to replace it with 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()));
                     
                    }

                }
            }

Guess you like

Origin blog.csdn.net/m0_49412847/article/details/124665562