If you are using JDK 1.7 or JDK 1.8, you can use the NIO API. 2.
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 java.nio.file.FileSystem, you can call the method to get the file system for the JAR file.
To access the files inside your JAR file, you can use the following method, which then allows you to read the files, but you may want to.
fileSystem.getPath("/images/image.gif")
If you want to be able to run this in Eclipse, make sure you surround the method call with an IOException try / catch and assign your FileSystem object as follows.
new File(Start.class.getProtectionDomain().getCodeSource().getLocation().toURI()) .toPath().toString();
This will allow you to run your program, whether it is compressed into a JAR file or not.
I recommend that you get used to using NIO.2, as it is a very powerful API.
source share