如何獲取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路徑。 還能使用~../ 等路徑的跳轉。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章