ziptest

package test;


import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 动态生成HTML文件,并压缩在一个ZIP文件中
 *
 * @author lenovo
 *
 */
public class ZIPTest
{
 public static void main(String[] args) throws IOException
 {
  String classPath = ZIPTest.class.getResource("").toString();
  // 路径
  String filePath = classPath.substring(classPath.indexOf("/") + 1);
  // 生成的文件名称
  String fileName = "e://testzip.zip";

  generateZipFile(fileName);
 }

 /**
  * Generate zip file.
  *
  * @param fileName
  *            the file name
  * @param zipFile
  *            the zip file
  * @throws IOException
  *             Signals that an I/O exception has occurred.
  */
 private static void generateZipFile(String fileName) throws IOException
 {
  // 在声明ZipEntry的时候在name后加上文件类型后缀,不然解压后的文件没有文件后缀。
  String files[] = { "test1.html", "test2.html" };

  // 声明ZipOutputStream,用来输出zip文件。
  ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
    fileName));
  

  // 构建html,并添加数据
  StringBuffer strHtml = new StringBuffer();
  strHtml.append("<html>");
  strHtml.append("<title>testziphello</title>");
  strHtml.append("<body>test hello!<a href=" + "test2.html"
    + ">test2</a></body>");
  strHtml.append("</html>");

  // 构建另一个html,并添加数据
  StringBuffer strHtml2 = new StringBuffer();
  strHtml2.append("<html>");
  strHtml2.append("<title>testziphello</title>");
  strHtml2.append("<body>test2 hello!</body>");
  strHtml2.append("</html>");

  String[] datas = new String[]{ strHtml.toString(), strHtml2.toString() };
  for (int i = 0; i < files.length; i++)
  {

   // 向压缩文件中输出数据
       // Add ZIP entry to output stream.
   // 声明ZipEntry
   zipOut.putNextEntry(new ZipEntry(files[i]));

   // Add ZIP entry to output stream.
   zipOut.write(datas[i].getBytes());
   
   // Complete the entry
   zipOut.closeEntry();

  }

  zipOut.close();

  System.out.println("Successfully!");
 }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值