Exporting Images with JAR in Eclipse (Java)

后端 未结 6 1960
无人及你
无人及你 2020-12-06 22:45

I\'ve been working on a little project that requires external images for display. I\'m not all that familiar with how to use Eclipse and this is my first time attempting to

相关标签:
6条回答
  • 2020-12-06 23:09

    you might need to load them as class path resources if they are within a jar. see: getClass().getClassLoader().getResourceAsStream(...)

    0 讨论(0)
  • 2020-12-06 23:14

    Something I would have found useful with this answer is the following: make sure you put your images/files in the same eclipse folder (or sub-folder below) as your source code. I created a folder "images_ignored" using eclipse, added it to the build path but still it refused to be included in my JAR file (when creating an executable JAR).

    Eclipse screenshot showing were to put images

    0 讨论(0)
  • 2020-12-06 23:17

    Use getResource() to load the images:

    ImageIcon qmarkIcon = new ImageIcon(getClass().getResource("images/mark.gif"));
    
    0 讨论(0)
  • 2020-12-06 23:22

    Just drag the images folder into your Eclipse project, then choose to "Copy New Folder" or "Copy File and Folder" depending on Eclipse version, and then right click on the image folder (in Eclipse) and --> build path "use as source folder".

    0 讨论(0)
  • 2020-12-06 23:28

    If you add a folder to build path you can retrieve the images either in eclipse and when you exported it in jar file, just remember to don't reference the image with the path like img/myImage.gif but only myImage.gif !

    0 讨论(0)
  • 2020-12-06 23:31

    If you're using JDK 1.7 or JDK 1.8, you might want to use the NIO.2 API.

    for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
        if ("jar".equals(provider.getScheme()))
            return provider.newFileSystem((new File(Start.class
                    .getProtectionDomain().getCodeSource().getLocation().toURI()))
                    .toPath(), new HashMap<String, Object>());
    }
    

    If you enter this code into a method that returns a java.nio.file.FileSystem, you can call the method to get the FileSystem for the JAR file.

    To get the path to access the files inside your JAR file, you can use the following method, which then allows you to read the files however you may want.

    fileSystem.getPath("/images/image.gif")
    

    If you would like to be able to run this in Eclipse, make sure you surround the call to the method with a try/catch IOException and assign to your FileSystem object the following.

    new File(Start.class.getProtectionDomain().getCodeSource().getLocation().toURI())
            .toPath().toString();
    

    This will allow you to run your program whether it's compressed into a JAR file or not.


    I recommend you get used to using NIO.2, since it is a very powerful API.

    0 讨论(0)
提交回复
热议问题