ziptest

来源:互联网 发布:淘宝虚拟发货怎么设置 编辑:程序博客网 时间:2024/06/05 21:58

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!");
 }

}

原创粉丝点击