2014-11-20 2 views
-2

나는 absPath에 액세스하는에서 FileNotFoundException이 발생,파일의 절대 경로에서 FileNotFoundException이 발생했습니다 (파일이 존재 함에도 불구하고). 왜요?

String absPath=this.getClass().getResource("/test.gif").toString(); 
System.out.print(Path);// prints the absolute path /Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif - the file exists at the location. 



String relPath= "src/main/resources/test.gif"; 

그러나 다음과 같은 방식으로는 ClassLoader를 사용하여 절대 경로를 사용하여 내 프로그램에서, 파일 (Eclipse에서 src/main/resources/test.gif)에 위치 test.gif에 액세스하기 위해 노력하고있어 내 프로그램을 사용하는 반면 relPath은 사용하지 않습니다.

내가 뭘 잘못하고 있니? 그리고 ClassLoader를 통해 절대 경로를 사용하여 파일에 올바르게 액세스하는 방법

+0

이'Users/[username]/Project/SubFolder'가 올바른 절대 경로라면, 앞에 슬래시가 없습니다. – Tom

+0

'Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif'는 절대 경로가 아닙니다. 처음에는'/'가 빠져 있습니다. – Mureinik

+0

가능한 중복 [어디에 내가 이클립스에서 사용하고 싶은 텍스트 파일을 넣을 까?] (http://stackoverflow.com/questions/2850674/where-to-put-a-textfile-i-want-to-use-in) -eclipse) – KNU

답변

0

상대 경로를 말하면서 "/test.gif"로 테스트하는 경로는 /로 시작합니다! 새 질문을 추가하기 전에 다른 응답을보십시오. 파일에 대한 절대 경로를 반환합니다 또한

URL url = getClass().getResource("/test.gif"); 
    File file = new File(url.toURI(); 
    System.out.println(file).getCanonicalPath()); 

, getCanonicalPath() : Preferred way of loading resources in Java

0

는 URL 및 파일 클래스를 사용합니다. 리소스를 찾을 수없는 경우 null을 확인해야 할 수 있습니다.

관련 문제