如何获取ClassPath路径下的配置文件

通常我们获取classpath路径下的文件使用如下的方式:

public class FileLoader {

   public boolean exists() throws IOException {
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/BaseMapper.xml");
        if (resourceAsStream == null) {
            return false;
        }
        return resourceAsStream.available() > 0;
    }

    public static void main(String[] args) throws IOException {
        FileLoader f = new FileLoader();
        System.out.println(f.exists());
    }

}

注意不要使用getResource方法, getResource在idea中没有问题,但是如果打成jar包后就会找不到文件.

下面是我写的一个遍历传入class类下的所有类的方法。 对于jar包中的文件可以使用JarFile类来获取


   private List<String> findAllClassName(Class clazz) throws IOException {
   	//获取传入的class类的文件路径地址
       String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
       String aPackage = clazz.getPackage().getName();
       String prefixPackagePath = aPackage.replaceAll("\\.", "/");
       List<String> classFiles = new ArrayList<>();
       //根据这个地址的后缀来判断 是否是jar包, 如果jar包就使用JarFile类来读取文件
       if (path.endsWith(".jar")) {
           try (JarFile jarFile = new JarFile(path)) {
               Enumeration<JarEntry> entries = jarFile.entries();
               while (entries.hasMoreElements()) {
                   JarEntry jarEntry = entries.nextElement();
                   String name = jarEntry.getName();
                   if (name.endsWith(".class") && name.startsWith(prefixPackagePath)) {
                       name = name.substring(0, name.length() - 6);
                       classFiles.add(name.replaceAll("/", "."));
                   }
               }
           }
       } else {
           File file = new File(path + prefixPackagePath);
           //使用了递归调用
           classFiles = finalClassName(file, aPackage);
       }
       return classFiles;
   }

Spring 获取jar包中classpath文件

		//获取容器资源解析器
        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();
		}	

PathMatchingResourcePatternResolver 是spring提供的一个获取classPath路径下资源的一个类 。它同样可以获取到jar包中的文件。

Hutool中获取资源文件

public class FileLoader {
 
    public boolean exists(){
        Resource resourceObj = ResourceUtil.getResourceObj("classpath:/BaseMapper.xml");
        URL resource = resourceObj.getUrl();
        if(resource==null){
            return false;
        }
        File f = new File(resource.getFile());
        return f.exists();
    }
    public static void main(String[] args) throws IOException {
        FileLoader f = new FileLoader();
        System.out.println(f.exists());
    }
 
}

hutool是一个十分好用的java工具包。 里面也有方便的获取classpath路径的工具ResourceUtil。 并且ResourceUtil还能兼容windows路径。 还能使用~../ 等路径的跳转。

猜你喜欢

转载自blog.csdn.net/leisurelen/article/details/106780633