如题:
现在在做一个类似于rar那种的压缩工具。
首先先介绍一下我的做法
1、先将已有jar文件通过流读出来(这里旧jar文件暂定A.jar)
2、建立一个输出新的输出文件B.jar
3、将A.jar中的文件clone到B.jar中
4、将新文件a.txt写入B.jar中
5、删除A.jar.
6、将B.jar名称修改为A.jar但是如上所做会出现一些问题
1、如果A.jar文件很大的话,那么添加一个新文件的时间就会很长
2、在删除A.jar后如果断电等异常出现,就不能实现新文件的写入希望各位高手能够提供点建议,或者新的思路、代码
谢谢!!!
现在在做一个类似于rar那种的压缩工具。
首先先介绍一下我的做法
1、先将已有jar文件通过流读出来(这里旧jar文件暂定A.jar)
2、建立一个输出新的输出文件B.jar
3、将A.jar中的文件clone到B.jar中
4、将新文件a.txt写入B.jar中
5、删除A.jar.
6、将B.jar名称修改为A.jar但是如上所做会出现一些问题
1、如果A.jar文件很大的话,那么添加一个新文件的时间就会很长
2、在删除A.jar后如果断电等异常出现,就不能实现新文件的写入希望各位高手能够提供点建议,或者新的思路、代码
谢谢!!!
JarOutputStream jarOut = null;
JarInputStream jarIn = null;
FileInputStream fileIn = null;
try {
File file = new File(inputJar); //inputJar已有的压缩文件
//这样做会已有的压缩文件就会被覆盖了
jarOut = new JarOutputStream(new FileOutputStream(inputJar));
jarIn = new JarInputStream(new FileInputStream(file));
http://topic.csdn.net/u/20080708/19/1ca6881f-1736-4f2f-8554-0a12853472ae.html
public static void addFilesToExistingZip(File zipFile,
File[] files) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete(); boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
for (int i = 0; i < files.length; i++) {
InputStream in = new FileInputStream(files[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(files[i].getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
tempFile.delete();
}
Ant -> Avalon-Excalibur -> Commons-IO -> Commons-Compress.