클래스 경로 리소스 (XML 파일)에서 입력 스트림 가져 오기
Java 웹 애플리케이션에서 CLASSPATH (즉, 소스 폴더 내부)에있는 XML 파일의 InputStream을 가져 오려면 어떻게해야합니까?
ClassLoader.getResourceAsStream()
.
아래 주석에서 언급했듯이 다중 ClassLoader
환경 (예 : 단위 테스트, 웹 앱 등)에있는 경우 Thread.currentThread().getContextClassLoader()
. http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388을 참조 하십시오 .
ClassLoader.class.getResourceAsStream("/path/file.ext");
그것은 정확히 XML 파일이 어디에 있는지에 달려 있습니다. 소스 폴더 ( "기본 패키지"또는 "루트")에 있습니까? 아니면 클래스와 같은 폴더에 있습니까?
전자의 경우 /file.xml
파일을 찾기 위해 " "(선행 슬래시에 유의)를 사용해야 하며 파일을 찾으려고 시도하는 데 사용하는 클래스는 중요하지 않습니다.
XML 파일이 클래스 옆에 있으면 파일 SomeClass.class.getResourceAsStream()
이름 만 사용하면됩니다.
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
컴파일 스크립트가 CLASSPATH에 xml 파일을 복사하고 있는지 확인하십시오.
someClassWithinYourSourceDir.getClass (). getResourceAsStream ();
이 답변의 "getResourceAsStream ()"옵션 중 일부는 저에게 작동하지 않았지만이 옵션은 작동했습니다.
SomeClassWithinYourSourceDir.class.getClassLoader (). getResourceAsStream ( "yourResource");
제안 된 솔루션을 시도했지만 파일 이름에 슬래시가 작동하지 않았습니다. 예 : ... (). getResourceAsStream ( "/ my.properties"); null이 반환되었습니다.
슬래시 제거가 작동했습니다. .... getResourceAsStream ( "my.properties");
다음은 doc API에서 가져온 것입니다. 위임 전에이 알고리즘을 사용하여 주어진 리소스 이름에서 절대 리소스 이름이 구성됩니다.
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
'program story' 카테고리의 다른 글
Java에 조건부 및 조건부 또는 연산자의 복합 할당 버전이없는 이유는 무엇입니까? (0) | 2020.10.15 |
---|---|
Node.js 및 AngularJS 애플리케이션 구조화 (0) | 2020.10.15 |
Integer와 int를 비교하면 Java에서 NullPointerException이 발생할 수있는 이유는 무엇입니까? (0) | 2020.10.14 |
MySQL : SQL 쿼리의 각 결과에 대한 레코드를 삽입하는 방법은 무엇입니까? (0) | 2020.10.14 |
PHP-클래스 내부에 상수 정의 (0) | 2020.10.14 |