2013-07-04 74 views
0

我嘗試從運行jar中複製jar文件,它可以在eclipse IDE中運行,但不是在外部運行jar應用程序時。代碼的下面部分:從運行jar應用程序內部失敗的複製jar文件

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(); 

請幫助,感謝您的建議,以解決上述問題

回答

0

它是使用像簡單的代碼來解決:

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); 

我得到線索從How to copy file inside jar to outside the jar? 非常感謝。