백엔드 (Back-End)/자바 ( JAVA )

[JAVA] 텍스트 파일 불러와 내용 읽기

xxvigrufv 2022. 7. 6. 15:57
반응형
@GetMapping("/default.txt")
    public ResponseEntity<Resource> readDefaultTxt(@RequestParam Map<String, String> param) {
        
        //파일이 저장된 폴더 경로 변수 선언
        String fileRoot = "";


        // os 정보 확인 및 사진이 저장된 서버 로컬 경로 지정 실시
        
        if(os.contains("win")) {
            fileRoot = "c:/Home/Resource/assets/"; //윈도우 경로 (디스크 필요)
        }
        else if(os.contains("linux")) {
            fileRoot = "/Home/Resource/assets/"; //리눅스 경로
        }

        fileRoot = fileRoot + String.valueOf(param.get("file"));
      
        // Resorce를 사용해서 로컬 서버에 저장된 이미지 경로 및 파일 명을 지정
        Resource resource = new FileSystemResource(fileRoot);


        // 로컬 서버에 저장된 파일이 없을 경우
        if(!resource.exists()){
			return new ResponseEntity<Resource>(HttpStatus.NOT_FOUND);
		}

        // 로컬 서버에 저장된 이미지가 있는 경우 로직 처리
        HttpHeaders header = new HttpHeaders();
        Path filePath = null;
		
        try {
            filePath = Paths.get(fileRoot);
            // 인풋으로 들어온 파일명 .png / .jpg / .txt 에 맞게 헤더 타입 설정
            header.add("Content-Type", Files.probeContentType(filePath));
        }
        catch (Exception e){
            e.printStackTrace();
        }
        // 파일 리턴 실시 [브라우저에서 get 주소 확인 가능]
        return new ResponseEntity<Resource>(resource, header, HttpStatus.OK);
    }

 


< 실제 적용 코드 >

 

	//Sparrow Cloud key 조회 Api 
	@GetMapping(value = "/sparrow-cloud-key-1952.txt", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public  ResponseEntity<Resource> GetSparrowCloudKey1952(Locale locale, HttpServletRequest request, 
			HttpServletResponse response, HttpSession session) throws IOException {
			
		log.debug("[API CALLED] : /sparrow-cloud-key-1952.txt");

		//서버 로컬 경로 지정
		String existingUploadPath = context.getRealPath("/resources");
		System.out.println(existingUploadPath);
		// 파일명 지정
		final String existingFileName = "sparrow-cloud-key-1952.txt";
		
		//서버 로컬 경로 + 파일 명 저장 실시
		Path path = Paths.get(existingUploadPath + File.separator + existingFileName);
		
		Resource resource = new FileSystemResource(path);
		
		log.debug(path.toString());
		List<String> content  = Files.readAllLines(path, StandardCharsets.UTF_8);         
		System.out.println(content);
						
		return new ResponseEntity<Resource>(resource, HttpStatus.OK);
	}
반응형