🚀 from error to study/Java

[JAVA] java.net.MalformedURLException: unknown protocol: c 오류 해결법

천재강쥐 2024. 11. 10. 15:33


 
  

🔥 포스팅 계기

 

톰캣을 올릴 때 오류 발생!
원인을 찾아보니 구글 연동 키 파일을 로컬 경로로 불러올 때 문제로 보였음

 

 
 
 

📍 문제 원인

PRIVATE_KEY_FILE_PATH=C:/devUtil/cert/privateKey.der

👉🏻 구글 연동을 위한 키 파일을 프로퍼티 파일에 위와 같이 정의해 줬었음 
 
👉🏻 리눅스의 경우 아래와 같이 불러 줘도 문제가 없음

biz/google/cert/privateKey.der

 
👉🏻 하지만 윈도우의 경우 대다수의 경로가 C 혹은 D 드라이브를 타기 때문에 C:나 D:로 시작함
👉🏻 앞에 file:/// 이라는 prefix를 붙여 주지 않으면 C를 URL 프로토콜로 인식한다고 함
 
 
 
 

📍 해결법

PRIVATE_KEY_FILE_PATH=file:///C:/devUtil/cert/privateKey.der

👉🏻 하라는 대로 앞에 "file:///"을 붙여 준 뒤 톰캣 재기동 시에는 오류가 발생하지 않았음

 
 
 

💻 (추가) 윈도우나 리눅스에서 경로와 파일명은 어떻게 분석할까?

👉🏻 궁금한 점이 생겼다.
👉🏻  각 경로를 /(슬래시, 윈도우의 경우 \도 포함)로 나누고, 가장 마지막 /(슬래시) 뒤는 잘라서 파일명으로 보지 않을까?
👉🏻  이걸 로직으로 어떻게 풀 수 있을까?

 

✔️ 파일명에 prefix로 file:///가 정상적으로 들어간 경우

(해당 테스트는 자바에서만 진행했기 때문에 userAgent 등을 쓰지 못하여 윈도우 기준으로만 살펴보았다!)

public class Test {

	public static void main(String[] args) {
		
		// 파일명 앞에 file:///을 붙였을 때
		String originPath = "file:///C:/devUtil/cert/privateKey.der";
		System.out.println("originPath: " + originPath);
		
		// 파일명이 정상이라면
		if(originPath.startsWith("file:///")) {
			
			// 슬래시(/) 중 가장 마지막 인덱스 찾기
			int lastIndex = originPath.lastIndexOf('/');
			System.out.println("last / index: " + lastIndex);
			
			// 마지막 슬래시(/) 인덱스 앞까지가 파일 경로
			String path = originPath.substring(0, lastIndex);
			System.out.println("path: " + path);
			
			// 마지막 슬래시(/) 인덱스 뒤부터 파일명
			String fileName = originPath.substring(lastIndex + 1);
			System.out.println("fileName: " + fileName);
			
		} else { // prefix가 없다면
			String protocol = originPath.substring(0, 1).toLowerCase();
			System.out.println("java.net.MalformedURLException: unknown protocol: " + protocol);
		}
		
	}

}

 
 

✔️ 파일명에 prefix로 file:///가 정상적으로 들어가지 않은 경우

(해당 테스트는 자바에서만 진행했기 때문에 userAgent 등을 쓰지 못하여 윈도우 기준으로만 살펴보았다!)

public class Test {

	public static void main(String[] args) {
		
		// 파일명 앞에 file:///을 붙였을 때
		String originPath = "C:/devUtil/cert/privateKey.der";
		System.out.println("originPath: " + originPath);
		
		// 파일명이 정상이라면
		if(originPath.startsWith("file:///")) {
			
			// 슬래시(/) 중 가장 마지막 인덱스 찾기
			int lastIndex = originPath.lastIndexOf('/');
			System.out.println("last / index: " + lastIndex);
			
			// 마지막 슬래시(/) 인덱스 앞까지가 파일 경로
			String path = originPath.substring(0, lastIndex);
			System.out.println("path: " + path);
			
			// 마지막 슬래시(/) 인덱스 뒤부터 파일명
			String fileName = originPath.substring(lastIndex + 1);
			System.out.println("fileName: " + fileName);
			
		} else { // prefix가 없다면
			String protocol = originPath.substring(0, 1).toLowerCase();
			System.out.println("java.net.MalformedURLException: unknown protocol: " + protocol);
		}
		
	}

}