我试图从运行jar中复制jar文件,在eclipse IDE中运行是可以的,但在外部运行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();
请帮助并感谢您的建议来解决上述问题
它使用简单的代码来解决,如:
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);
我从如何将文件复制到罐子外得到了线索?非常感谢。