怎么将一个文本文件压缩到一个zip文件中啊?
我的问题是:我现在可以将新的文本文件压缩到一个指定的压缩文件,但压缩文件中以前的文件就没有了,怎么回事呢?
比如有个压缩文件为 file.zip,里边由a.txt和b.txt两个文件。
现在将c.txt压缩到里边,但压缩完成后,file.zip中只有c.txt文件了,怎么回事呢?
File file = new File(fileName);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
log.error( "文件创建错误 " + e.getMessage());
e.printStackTrace();
}
}
FileOutputStream fout = new FileOutputStream(file);
ZipOutputStream zout = new ZipOutputStream(fout);
DateFormat df=DateFormat.getDateTimeInstance();
String fdate = df.format(new java.util.Date());
zout.setMethod(ZipOutputStream.DEFLATED);
zout.putNextEntry(new ZipEntry( "111 "));
//测试
byte[] b = new byte[3];
b = new String( "123 ").getBytes();
byte[] v = new byte[2];
v = new String( "\r\n ").getBytes();
zout.write(b,0,b.length);
zout.write(v,0,v.length);
zout.write(b,0,b.length);
zout.flush();
zout.close();
fout.close();
[解决办法]
找个中间产物吧.
import java.util.Enumeration;
import java.util.zip.*;
import java.io.*;
public class ZIO {
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
new ZIO().add( "C:/a.zip ", "C:/a.txt ");
}
public void add(String src,String addFile) throws Exception
{
ZipFile zf=new ZipFile(src);
File tempf;
Enumeration e=zf.entries();
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(tempf=File.createTempFile( "tmp ", "zip ")));
while(e.hasMoreElements())
{
ZipEntry ze=(ZipEntry) e.nextElement();
zos.putNextEntry(ze);
int temp;
InputStream ist=zf.getInputStream(ze);
while((temp=ist.read())!=-1)zos.write(temp);
ist.close();
zos.closeEntry();
}
zf.close();
zos.putNextEntry(new ZipEntry(new File(addFile).getName()));
FileInputStream ff=new FileInputStream(addFile);
int r=0;
while((r=ff.read())!=-1)
{
zos.write(r);
}
zos.closeEntry();
zos.close();
new File(src).delete();
tempf.renameTo(new File(src));
tempf.delete();
}
}