ResourceUtils.getFile 获取文件 获取jar包中的资源文件

摘要:通过Spring工具类获取classpath下的文件资源;获取jar包中的资源文件

1. web项目下classpath文件获取

  方法(1)File resourcefile = ResourceUtils.getFile("classpath:application.properties");

  方法(2) Resource resourcefile = new ClassPathResource("application.properties");

  获取文件:resourcefile .getFile()  /  获取文件流:resourcefile .getInputStream();

2. 获取web项目jar包中文件:

方法(1) :Resource fileRource = new ClassPathResource("application.properties");

获取文件流:fileRource.getInputStream();

方法(2) :Thread.currentThread().classLoader().getResourceAsstream()

private String readFileByLines(String filePath) throws Exception {
        StringBuffer str = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(findClassLoader().getResourceAsStream(filePath)
                    , "UTF-8"));
            String tempString = null;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                str = str.append(" " + tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return str.toString();
    }

 /**
     * 配合api读取linux环境下jar包中的文件路径
     * @return
     */
    private ClassLoader findClassLoader(){
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if(loader==null){
            loader = ClassLoader.getSystemClassLoader();
        }
        return loader;
    }

Class.getResource("")获取的是相对于当前类的相对路径

Class.getResource("/")获取的是classpath的根路径

ClassLoader.getResource("")获取的是classpath的根路径 

 

 

你可能感兴趣的:(ResourceUtils.getFile 获取文件 获取jar包中的资源文件)