简体   繁体   中英

How can I get files in .jar file using java?

My problem is getting some CSS files from a foo.jar file. How can I get these CSS files from foo.jar? I found some ways, firstly by unzipping this .jar and copying files and then by deleting the unzipped folder. Is that a good way?

My JAR file location is C:\\foo.jar

public static void main(String[] args) throws IOException {
        {
            URL url = getClass().getClassLoader().getResource("css/demo.css");
            URL url2 = getClass().getClassLoader().getResource("");
            System.out.println("url = " + url);
            System.out.println("url_2 = " + url2);

        }
    }

Output:

url = jar:file:/C:/foo.jar!/css/demo.css

url_2 = file:/C:/

So, I don't need to extract foo.jar. I can copy files within JAR like this way. Thank you.

The following example will make you clear Let's extract some files from the TicTacToe JAR file we've been using in previous sections. Recall that the contents of TicTacToe.jar are:

META-INF/MANIFEST.MF
TicTacToe.class
TicTacToe.class
TicTacToe.java
audio/
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au
example1.html
images/
images/cross.gif
images/not.gif

Suppose you want to extract the TicTacToe class file and the cross.gif image file. To do so, you can use this command:

jar xf TicTacToe.jar TicTacToe.class images/cross.gif

This command does two things:

It places a copy of TicTacToe.class in the current directory. It creates the directory images, if it doesn't already exist, and places a copy of cross.gif within it.

The original TicTacToe JAR file remains unchanged.

As many files as desired can be extracted from the JAR file in the same way. When the command doesn't specify which files to extract, the Jar tool extracts all files in the archive. For example, you can extract all the files in the TicTacToe archive by using this command:

jar xf TicTacToe.jar

Put that jar into the class path of the project. Then you can access the resources you needed.

The basic command to use for extracting the contents of a JAR file is:

jar xf myjarfile.jar;

for more info please check this link out :

http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM