เมื่อโหลดทรัพยากรให้แน่ใจว่าคุณสังเกตเห็นความแตกต่างระหว่าง:
getClass().getClassLoader().getResource("com/myorg/foo.jpg") //relative path
และ
getClass().getResource("/com/myorg/foo.jpg")); //note the slash at the beginning
ฉันเดาว่าความสับสนนี้ทำให้เกิดปัญหาส่วนใหญ่เมื่อโหลดทรัพยากร
นอกจากนี้เมื่อคุณกำลังโหลดรูปภาพจะใช้งานง่ายกว่าgetResourceAsStream():
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/com/myorg/foo.jpg"));
เมื่อคุณต้องโหลดไฟล์ (ไม่ใช่ภาพ) จากไฟล์เก็บถาวร JAR คุณอาจลองทำสิ่งนี้:
File file = null;
String resource = "/com/myorg/foo.xml";
URL res = getClass().getResource(resource);
if (res.getProtocol().equals("jar")) {
    try {
        InputStream input = getClass().getResourceAsStream(resource);
        file = File.createTempFile("tempfile", ".tmp");
        OutputStream out = new FileOutputStream(file);
        int read;
        byte[] bytes = new byte[1024];
        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.close();
        file.deleteOnExit();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
} else {
    //this will probably work in your IDE, but not from a JAR
    file = new File(res.getFile());
}
if (file != null && !file.exists()) {
    throw new RuntimeException("Error: File " + file + " not found!");
}