我尝试从运行的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();
请帮助并感谢您提出解决上述问题的建议
答案 0 :(得分: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?得到了线索 非常感谢。