SpringBoot访问资源文件

    技术2022-07-10  143

    假设资源文件如下

    一、获取某个具体文件资源时,可用以下两种方式:

    1.直接获取输入流:

    InputStream resourceAsStream = getClass().getResourceAsStream("/templates/addAgentAccount.bpmn");//开头必须带斜杠

    2.获取输入流、文件名等等

    ClassPathResource classPathResource = new ClassPathResource( "/templates/addAgentAccount.bpmn");//开头有无斜杠都可以 System.out.println(classPathResource.getInputStream()); System.out.println(classPathResource.exists()); System.out.println(classPathResource.getFilename()); System.out.println(classPathResource.contentLength()); System.out.println(classPathResource.isFile());

    二、获取某目录下所有资源:(注意,路径前要带上classpath:且后面带上通配符)

    Resource[] resources = new PathMatchingResourcePatternResolver() .getResources("classpath:templates/*");

    三、获取Jar包所在目录

    public static String TARGET_PATH = new ApplicationHome(getClass()).getSource() .getParentFile().toString();

     

    Processed: 0.011, SQL: 9