방법 1: ClassLoader.getResource() 메서드 사용
String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getClassLoader().getResource(filePath);
String resourcePath = resourceUrl.getPath();
방법 2: ClassLoader.getResourceAsStream() 메서드 사용
String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
방법 3: Class.getResource() 메서드 사용
String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getResource(filePath);
String resourcePath = resourceUrl.getPath();
방법 4: Class.getResourceAsStream() 메서드 사용
String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getResourceAsStream(filePath);
문제기록
리소스 디렉터리에서 파일 경로를 가져오고 반환
public String getResourcesPath(String filePath) {
String resourcePath=null;
try {
Resource resource = new ClassPathResource(filePath);
Path path = resource.getFile().toPath();
resourcePath=path.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
return resourcePath;
}
파일 경로는 여기에서도 얻을 수 있습니다. 로컬만 가능합니다. jar 패키지를 사용할 때 파일의 특정 경로를 얻을 수 없습니다. 내 솔루션은 다음과 같습니다.
public String getResourcesPath(String filePath) {
String resourcePath=null;
File file = new File(filePath);
try {
Resource resource = new ClassPathResource(filePath);
InputStream inputStream = resource.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
resourcePath=file.getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException(e);
}
return resourcePath;
}
스트림에서 가져오기