springboot打成jar后获取classpath下的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huyande123/article/details/81284941

直接上代码  

JAR包用这个

		//获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		// 获取远程服务器IP和端口
		try {
			//获取所有匹配的文件
            Resource[] resources = resolver.getResources("static/images/faceSearch/*.*");
            for(Resource resource : resources) {
                //获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
                InputStream stream = resource.getInputStream();
                if (log.isInfoEnabled()) {
                	log.info("读取的文件流  [" + stream + "]");
                }
                String targetFilePath =env.getProperty("faceSearchDemo.faceSerachPics")+resource.getFilename();
                if (log.isInfoEnabled()) {
                	log.info("放置位置  [" + targetFilePath + "]");
                }
                File ttfFile = new File(targetFilePath);
                if(!ttfFile.getParentFile().exists()) {
                	ttfFile.getParentFile().mkdir();
                }
                FileUtils.copyInputStreamToFile(stream, ttfFile);
            }
		}catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}	

因为Springboot会将项目 打成 jar包,所以用下面的代码来获取文件,在本地eclipse上是可以运行获得到的,但在服务器上是不行的,必须要使用上面的代码。

WAR可以用这个

File file = ResourceUtils.getFile("classpath:static/images/faceSearch");
 if (file.exists()) {
	File[] files = file.listFiles();
	List<String> imageList = new ArrayList<>();
	if (files != null) {
		for(File fileC :files) {
			imageList.add(fileC.getName());
		}
	}
model.addAttribute("faceSerachImgList", imageList);

猜你喜欢

转载自blog.csdn.net/huyande123/article/details/81284941
今日推荐