如何从URL中提取jar文件

时间:2016-06-06 05:36:52

标签: java jar

我有一个托管在云中的jar文件。我的要求是我要将jar提取到我的本地机器中。我已经编写了一个代码来将jar提取到我的本地机器中。但是它需要找到jar的位置在我的本地机器上。像我浪费机器空间,因为我所做的是从给定的URL输入流创建一个jar。(将jar文件复制到我的本地机器(物理文件可以在我的机器中找到))

url = new URL("https://myres/jarFile.jar");
InputStream in = new BufferedInputStream(url.openStream());
java.nio.file.Files.copy(in,"temp.jar");

我的要求是,我不是这样做,而是如何从URL输入流中将jar文件提取到我的机器中。然后无需将URL jar物理复制到我的机器中。只需包含提取的jar文件。

提取jar的代码

public String extractJar(String input){

 Path dirPath = Paths.get("location for file to be copy");
    JarFile jar;
    URL url;
    try {

        url = new URL(input);
        InputStream in = new BufferedInputStream(url.openStream());
        java.nio.file.Files.copy(in, dirPath.resolve("temp.jar"));//I want to skip this step


        jar = new JarFile(dirPath.resolve("temp.jar").toString());

        Enumeration<JarEntry> enumEntries = jar.entries();
         while (enumEntries.hasMoreElements()) {

         JarEntry file = enumEntries.nextElement();
        File f = new File(dirPath + File.separator + file.getName());

                    // Check if file is a Dir
                    if (file.isDirectory()) {
                        f.mkdirs();
                        continue;
                    }

                    InputStream is = jar.getInputStream(file);
                    FileOutputStream fos = new FileOutputStream(f);

                    // Write contents
                    while (is.available() > 0) {
                        fos.write(is.read());

                    }

                    fos.close();
                    is.close();
                }
                } catch (IOException e) {

                    e.printStackTrace();
                    throw new ResourceNotFoundException(e.getMessage());
                }
                return dirPath.toAbsolutePath().toString();

}

1 个答案:

答案 0 :(得分:1)

试试这个:

public static void extractAllEntries(String urlPath, String destination) {
    try {
        byte[] buffer = new byte[1024];
        InputStream input = new URL(urlPath).openStream();
        JarInputStream jin = new JarInputStream(input);
        ZipEntry entry;

        while ((entry = jin.getNextEntry()) != null) {
            ZipEntry file = (ZipEntry) entry;
            File f = new java.io.File(destination + java.io.File.separator
                    + file.getName());
            if (file.isDirectory()) {
                f.mkdir();
                continue;
            }
            FileOutputStream fos = new FileOutputStream(f);
            int len;
            while ((len = jin.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
        }
        jin.closeEntry();
        jin.close();
        input.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我只是大致编码..请正确处理finally子句中输入流的关闭。