[web-019]在springboot的jar包里静态读取资源文件

在jar包不能用文件读,只能用流读。下面是直接可运行的demo

1.目录结构
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── hello
│   │   │       ├── Application.java
│   │   │       ├── Controller.java
│   │   │       └── DemoResReader.java
│   │   └── resources
│   │       └── pmml
│   │           └── a.pmml
 

2.pom.xml文件



    4.0.0

    org.springframework
    gs-rest-service
    0.1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.jayway.jsonpath
            json-path
            test
        
    

    
        1.8
    


    
        
            
                src/main/resources
                
                    **/*.*
                
                true
            
        

        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


3.Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4.Controller.java

package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @RequestMapping("/")
    public String greeting() {
        new DemoResReader();
        return "123";
    }
}

5.DemoResReader.java

package hello;


import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DemoResReader {

    public DemoResReader() {

        Resource resource = new ClassPathResource("pmml/a.pmml");
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = br.readLine())!= null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

}

6.a.pmml文件

aaa
aa
a

 

你可能感兴趣的:(spring,boot,资源文件,静态)