简体   繁体   中英

failed copy jar file from inside running jar application

I try to copy jar file from within running jar, it was okay running inside eclipse IDE, but NOT when running jar application outside. Here part of the codes :

AWdir = new File("C:\\Windows\\Temp\\aw\\");
    AWdir.mkdir();
    if(AWdir!=null && !AWdir.isDirectory()){
        MessageDialog.openError(getShell(), "Error create directry", "DIR:"+AWdir);
    }
    String resource = "generate.jar";
    URL res = MainWindow.this.getClass().getResource(resource);
    fileJar = new File(res.getFile());
    JarFile jarFile=new JarFile(fileJar);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destFile = new File(AWdir, fileNameLastPart);

    JarOutputStream jos = new JarOutputStream(new FileOutputStream(destFile));
    Enumeration<JarEntry> entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        InputStream is = jarFile.getInputStream(entry);
        //jos.putNextEntry(entry);
        //create a new entry to avoid ZipException: invalid entry compressed size
        jos.putNextEntry(new JarEntry(entry.getName()));
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = is.read(buffer)) != -1) {
            jos.write(buffer, 0, bytesRead);
        }
        is.close();
        jos.flush();
        jos.closeEntry();
    }
    jos.close();
    destFile.createNewFile();

please help and thank you for recommendation to resolve the above problem

it is solved using simple code like :

AWdir = new File("C:\\Windows\\Temp\\aw\\");
    AWdir.mkdir();
    if(AWdir!=null && !AWdir.isDirectory()){
        MessageDialog.openError(getShell(), "Error create directry", "DIR:"+AWdir);
    }
    String resource = "generate.jar";
    URL res = MainWindow.this.getClass().getResource(resource);   
//replace this line
    //fileJar = new File(res.getFile());
// become here
    fileJar = new File(AWdir.getAbsolutePath()+"\\"+"generate.jar");
//finally write down this
    FileUtils.copyURLToFile(res, fileJar);

i got clue from How to copy file inside jar to outside the jar? Thanks a lot.

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