将单个文件压缩成zip文件

loukcn 2007-10-07 12:33:38
就是将程序生成的文件再压缩成zip包,命名规则是原文件名的一部分,如:123-123-123.xml to 123-123.zip 请问各位该如何处理
...全文
95 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
shadao 2007-10-07
  • 打赏
  • 举报
回复

private void zip(File file) throws IOException {
if(!file.exists())
throw new FileNotFoundException();
if(file.isDirectory())
throw new FileNotFoundException();

String newName = file.getName();
if(newName.lastIndexOf('.')!=-1){
newName = newName.substring(0, newName.lastIndexOf('.'));
}

newName += ".zip";

File newFile = new File(file.getParent(),newName);

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(newFile));

ZipEntry ze = new ZipEntry(file.getName());

out.putNextEntry(ze);

FileInputStream in = new FileInputStream(file);

byte[] bfs = new byte[1024];
int rr;
while((rr = in.read(bfs))!=-1){
out.write(bfs, 0, rr);
}
in.close();


out.flush();

out.closeEntry();
out.close();
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧