if (ostream == null) {
if (outputFile == null) {
destfile = getConfigEntryResource().getFile();
if (destfile == null || !destfile.exists()) {
throw new ConfigException("Could not find " + getConfigEntryResource().getURL());
}
outputFile = new File(destfile.getParentFile(), destfile.getName() + ".tmp");
}
outputFile.getParentFile().mkdirs();
ostream = new BufferedOutputStream(new FileOutputStream(outputFile), 8192);
needCloseOutputStream = true;
}
// 检查或打开istream
if (istream == null) {
istream = getConfigEntryResource().getURL().openStream();
if (!(istream instanceof BufferedInputStream)) {
istream = new BufferedInputStream(istream, 8192);
}
needCloseInputStream = true;
}
zis = new ZipInputStream(istream);
zos = new ZipOutputStream(ostream);
ZipEntry zipEntry;
getGenerator().startSession(getConfigSettings().getPropertiesSet());
while ((zipEntry = zis.getNextEntry()) != null) {
allSuccess &= processZipEntry(zipEntry, zis, zos, dirs);
}
allSuccess &= getGenerator().getSession().generateLazyItems(new ZipCallback(zos, dirs));
getGenerator().getSession().checkNonprocessedTemplates();
getGenerator().getSession().generateLog(new ZipCallback(zos, dirs));
success = true;
} catch (IOException e) {
throw new ConfigException(e);
} finally {
getGenerator().closeSession();
// 结束zip文件,但不关闭流
if (zos != null) {
try {
zos.finish();
} catch (IOException e) {
}
}
// 仅当输入流是由当前entry亲自打开的,才关闭流
if (needCloseInputStream && istream != null) {
try {
istream.close();
} catch (IOException e) {
}
}
// 仅当输出流是由当前entry亲自打开的,才关闭流
if (needCloseOutputStream && ostream != null) {
try {
ostream.flush();
ostream.close();
} catch (IOException e) {
}
// 如果成功,则将临时文件改成正式文件,否则删除临时文件
if (success) {
// 仅当没有指定outputFile时才做下面的事
if (getOutputFile() == null) {
// 在windows下,观察到rename失败,因为lock的原因。过一会重试。
int retryTimes = 10;
boolean succ = false;
String message = String.format("Moving file %s to %s failed.", outputFile.getName(),
destfile.getName());
for (int i = 0; i < retryTimes; i++) {
destfile.delete();
succ = outputFile.renameTo(destfile);
if (succ) {
break;
}
getConfigSettings().warn(
String.format(message + " Wait 0.5s and try again...%d of %d", i + 1, retryTimes));
try {
System.gc();
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
if (!succ) {
throw new ConfigException(message);
}
}
} else {
outputFile.delete();
}