jar 패키지를 통해 SpringBoot 프로젝트를 시작한 후 프로젝트 루트 경로의 정적 리소스를 읽을 수 없음에 대해

서문: 이것은 프로젝트가 배포된 어젯밤에 발견되었습니다. 여기에 기록하세요.

jar 패키지를 통해 SpringBoot 프로젝트를 시작한 후 프로젝트 루트 경로의 정적 리소스를 읽을 수 없음에 대해

문제 설명

프로젝트를 배포한 후 테스트를 위해 프로젝트 페이지를 열어보니 쿼리 페이지가 쿼리에 실패하고 자동으로 오류 페이지로 넘어갔고, 로그를 보니 아래와 같이 파일 읽기에 실패했습니다.

에러 메시지

여기에 이미지 설명 삽입

읽을 파일이 있는 디렉토리

여기에 이미지 설명 삽입

파일 읽기 부분의 코드

    public String readFileContent() {
    
    
        File file = new File("src/main/resources/static/ticket/station_name.txt");
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();

        try {
    
    
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
    
    
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (reader != null) {
    
    
                try {
    
    
                    reader.close();
                } catch (IOException e1) {
    
    
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }

그 당시 이 파일은 로컬 테스트 중에도 읽을 수 있는데 왜 서버에서 찾을 수 없는지 상당히 혼란스러웠습니다. ? ?

해결책

인터넷을 확인하고 파일을 사용하여 서버에서 로컬 리소스를 얻는 데 문제가 있음을 발견했습니다.

이유:
Resources 디렉토리의 파일은 xxx.jar 파일에 존재하며 서버 디스크에 실제 경로가 없고 실제로는 jar 내부의 경로입니다.

해결 방법 1(바보 방법):
읽을 파일을 서버의 해당 디렉터리에 업로드하고 읽은 파일 경로를 서버의 파일에 해당하는 경로로 변경합니다.

솔루션 2:
다음과 같이 입력 스트림을 사용합니다.

    public String readFileContent() throws Exception{
    
    

        String filePath = "static/ticket/station_name.txt";
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();

        //文件读取
        inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String tempStr;
        while ((tempStr = reader.readLine()) != null) {
    
    
            sbf.append(tempStr);
        }
        reader.close();
        return sbf.toString();
    }
    public String readFileContent() throws Exception{
    
    

        String filePath = "static/ticket/station_name.txt";
        ClassPathResource resource = new ClassPathResource(filePath);
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();

        //文件读取
        inputStream = resource.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String tempStr;
        while ((tempStr = reader.readLine()) != null) {
    
    
            sbf.append(tempStr);
        }
        reader.close();
        return sbf.toString();
    }

여기서 사용된 경로는 리소스 아래의 경로라는 점에 유의해야 합니다.

추신: 내 개인 블로그로 이동하여 더 많은 콘텐츠를 볼 수도 있습니다.
개인 블로그 주소: Xiaoguan 동급생의 블로그

추천

출처blog.csdn.net/weixin_45784666/article/details/121450856