sitelink1 http://pmguda.com/514 
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  

Jar 파일에 리소스를 포함하여 배포하였을 경우 그 리소스에 접근하는 방법입니다.

예제코드:

package com.pmguda.resjar;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.*;

public class JarResourceLoading extends JFrame
    implements ActionListener {

    JButton button;
    ImageIcon buttonIcon;
    Clip buhClip;

    public final static String SOUND_PATH = "res/gudaMid.wav";
    public final static String IMAGE_PATH = "res/gudaImage.jpg";

    public JarResourceLoading () {
        super ("Resources from .jar");
        // get image and make button
        URL imageURL = getClass().getClassLoader().getResource (IMAGE_PATH);
        System.out.println ("found image at " + imageURL);
        buttonIcon = new ImageIcon (imageURL);
        button = new JButton ("Click to Buh!", buttonIcon);
        button.setHorizontalTextPosition (SwingConstants.CENTER);
        button.setVerticalTextPosition (SwingConstants.BOTTOM);
        button.addActionListener (this);
        getContentPane().add (button);
        // load sound into Clip
        try {
            URL soundURL = getClass().getClassLoader().getResource (SOUND_PATH);
            System.out.println ("found sound at " + soundURL);
            Line.Info linfo = new Line.Info (Clip.class);
            Line line = AudioSystem.getLine (linfo);
            buhClip = (Clip) line;
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL);
            buhClip.open(ais);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void actionPerformed (ActionEvent e) {
        System.out.println ("click!");
        if (buhClip != null) {
            buhClip.setFramePosition (0);
            buhClip.start();
        }
        else
            JOptionPane.showMessageDialog (this,
                                           "Couldn't load sound",
                                           "Error",
                                           JOptionPane.ERROR_MESSAGE);
    }

    public static final void main (String[] args) {
        JFrame frame = new JarResourceLoading();
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

그림 1.
jar.png

이클립스에서 jar 파일로 자동 배포 하였습니다. Jar 파일의 내부 구조도 이와 비슷하다.(압축을 풀어보면 알게된다.)

jar 파일안에 있는 이미지의 URL 은  Jar:file:/D:/resource.jar!/res/gudaImage.jpg

위의 코드에 대해 자세히 알아보고자 다른 자료를 찾아보았다.
다른 자료를 조금 인용하기 위해 긁어왔다.. 영문이다. ㅡㅡ;
해석해보면 그리 어렵지 않다. 위의 코드와 조금 다른 부분이 있을것이다. 잘 생각해 보자.


If you want to access a resource (configuration files, images, etc.) then you can certainly put it in a jar file, provided that jar file is in your classpath.

Then to access the resource, you can get a URL to it like this:
            URL url = this.getClass().getResource("/hello.jpg");
or you can get an InputStream to read it like this:
            InputStream is = this.getClass().getResourceAsStream("/app.properties");
Note that these methods will search for the resource in the directory tree relative to the package that "this" is in, so you will generally need the leading "/" to avoid that. But as for executable files in a jar file, forget it, there's no way to execute them from there. You can copy them out to a file and execute them from there, but that's the best you can do.


여기서 짚고 넘어가야 할 것은
패키지: com.pmguda.resjar
클래스: com.pmguda.resjar.JarResourceLoading
1.   getClass().getResource("gudaImage.jpg");
      현재 클래스의 위치에서 리소스를 찾는다
     클래스와 리소스의 위치가 같은 곳에 존재해야 한다.

2.   getClass().getResource("/res/gudaImage.jpg");
     패키지와 동일 루트에서 검색
3.   getClass().getClassLoader.getResource("res/gudaImage.jpg"); 
      패키지와 동일 루트에서의 상대 위치를 나타낸다.

java.lang.Class.getResource(String name)
Class.png

 

번역이 완전하지가 않아 이해하기 어려울듯 하다.

java.lang.Class.getResource(String name)에서
name 가 "/gudaImage.jpg" 일 경우 절대 경로명(/gudaImage.jpg)으로 사용되고
"gudaImage.jpg" 일 경우 현 클래스의 위치에서 시작하는 상대경로가 되겠지요 이를
절대경로로
나타내면 (/com/pmguda/resjar/gudaImage.jpg)

java.lang.ClassLoader.getResource(String name)
ClassLoader.png

1. getClass().getResource("/res/gudaImage.jpg"); 
2. getClass().getClassLoader.getResource("res/gudaImage.jpg"); 
동일한 URL을 리턴한다. 2번예시에서 앞에 "/" 을 넣어 시작하지 말도록 하자.
2번은 항상 상대경로만 인식하여 사용된다고 명심하시길..
ex)getClass().getClassLoader.getResource("/res/gudaImage.jpg");  

조금더 알아보고자 한다면 ClassLoader 에 대해 알아보는 것도 좋을듯 하다.

번호 제목 글쓴이 날짜 조회 수
33 File 클래스 정리 황제낙엽 2019.07.29 91
32 파일 사이즈를 반환하는 유틸 함수 황제낙엽 2019.07.29 120
31 BufferedReader, BufferedWriter를 활용한 빠른 입출력 황제낙엽 2019.07.29 77
30 File.length() 에 대하여 황제낙엽 2019.03.24 221
29 File.delete() 와 File.deleteOnExit() 황제낙엽 2019.03.24 1887
28 메일서버(daum.net)에 POP3를 이용하여 메일 가져오기 예제 file 황제낙엽 2018.10.09 940
27 org.apache.commons.io.FilenameUtils (getExtension) 황제낙엽 2018.04.01 1209
26 File 을 다루기 위한 유틸 클래스 file 황제낙엽 2018.02.28 99
25 HttpsURLConnection 을 사용한 SSL서버 접속 file 황제낙엽 2017.08.02 231
24 HttpURLConnection 사용 샘플( JSP , SERVLET ) 황제낙엽 2017.08.01 254
23 HttpURLConnection 사용하기 황제낙엽 2017.08.01 393
22 [HttpURLConnection] POST로 파라미터 넘기기 황제낙엽 2017.08.01 507
21 HttpURLConnection POST 방식 사용하기 황제낙엽 2017.08.01 370
20 servlet 에서의 json 한글처리 황제낙엽 2013.04.23 1519
19 com.oreilly.servlet.multipart 를 이용한 파일 업로드 file 황제낙엽 2013.03.19 104
» Jar파일에 포함된 리소스 접근하는 방법(How to read a resource from a JAR file ) file 황제낙엽 2012.06.24 164
17 16비트 CRC 체크용 클래스 (사용자 클래스) 황제낙엽 2010.03.14 406
16 파일을 읽어서 CRC 값을 연산하는 메서드 (java.util.zip.CRC32) 황제낙엽 2010.03.14 137
15 byte배열에 대한 CRC 를 계산하는 메서드 (java.util.zip.CRC32) 황제낙엽 2010.03.14 2166
14 org.apache.commons.fileupload.servlet.ServletFileUpload 를 이용한 파일 업로드 file 황제낙엽 2009.11.19 129