2013-11-03 3 views
0

이클립스 작업 공간에 JPanel 디스플레이를 만들고 있습니다. 나는 다음과 같은 코드가 있습니다.클래스와 같은 패키지에 이미지를로드하는 방법은 무엇입니까?

javax.imageio.IIOException: Can't read input file! 
:이 프로그램을 실행할 때
BufferedImage img = null; 
try { 
    img = ImageIO.read(new File("anno.png")); 
} catch (IOException e) {System.out.println(e);} 

그리고 이것은에있는 클래스와 같은 패키지에있는 파일 "anno.png"에

그러나 항상이 메시지를 보여줍니다

내가 뭘 잘못하고 있니?

답변

1

올바른 장소를보고 있지 않습니다. Java는 클래스 디렉토리가 아닌 사용자 디렉토리를 기반으로하는 디렉토리에서 파일을 찾습니다.

솔루션 :

  • 사용 자원 대신 파일. 리소스 디렉토리는 class 디렉토리를 기반으로합니다.
  • 또는 사용자 디렉토리가 무엇인지 알아보고 이미지에서 읽기 전에 파일 절대 경로를 인쇄하십시오.

나는 파일을 사용하지 않고 리소스를 선호합니다. 즉 getClass().getResourceAsStream("anno.png");

BufferedImage img = null; 
try { 
    img = ImageIO.read(getClass().getResourceAsStream("anno.png")); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
3

임베디드 리소스 (Jar 파일 또는 응용 프로그램 문맥 내 하나 reisdes) File를 사용하여 액세스 할 수없는 일반적으로. 대신, 당신은이 작업을 사용하지 않는 경우 ... 사용하여 그것을

img = ImageIO.read(getClass().getResource("anno.png")); 

시도 할 클래스 로더의 우리를 만들 필요가 ...

img = ImageIO.read(getClass().getResource("/path/to/anno.png")); 

대신

관련 문제