====== Java Classpath Resource ====== * [[http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html|Smartly load your properties - JavaWorld]] 이 문서 정리 * [[https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html|Accessing Resources]] * [[https://www.mkyong.com/java/java-read-a-file-from-resources-folder/|Java – Read a file from resources folder – Mkyong.com]] ===== Pure Java ===== ClassLoader.getResourceAsStream ("some/pkg/resource.properties"); // "/"가 없어도 절대경로 Class.getResourceAsStream ("/some/pkg/resource.properties"); // "/"가 없으면 상대경로 ResourceBundle.getBundle ("some.pkg.resource"); // 파일로 확보. jar로 묶여있을 경우 작동 안 할 수 있음. 주의 필요. File file = new File(getClass().getClassLoader().getResource("database.properties").getFile()); ===== SpringFramework Resource 사용 ===== * [[:springframework|Spring Framework]]의 [[https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ResourceLoader.html|ResourceLoader]] 를 사용하거나 [[https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html|ClassPathResource]] 같은 [[https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/Resource.html|Resource]]의 구현체를 직접 사용해도 된다. * [[https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html|ResourceUtils]]도 가능하다. Resource targetFileResource = new ClassPathResource("/package/to/myfile.txt"); File targetFile = targetFileResource.getFile(); // 혹은 File employeesFile = ResourceUtils.getFile("classpath:data/employees.dat"); * **classpath** 상의 리소스에 대해서 ''getFile()'' 은 매우 주의해야한다. ''jar'' 안에 묶여 있을 경우 ''getFile()''이 동작하지 않기 때문이다. * 따라서 ''getFile()'' 은 Test 코드 등에서만 사용하고, 실제 운영에서는 ''InputStream'' 으로만 읽도록 한다. ===== 참고 ===== * [[https://www.baeldung.com/spring-classpath-file-access|Access a File from the Classpath using Spring | Baeldung]]