欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中创建ZIP文件的方法

程序员文章站 2023-12-17 21:54:10
java创建zip文件的代码如下如下: import java.io.file; import java.io.fileinputstream; import...

java创建zip文件的代码如下如下:

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.zip.zipentry;
import java.util.zip.zipinputstream;
import java.util.zip.zipoutputstream;
public class zipdemo {
 public static void main(string[] args) throws ioexception {
  file file = new file("test.zip");
  if(!file.exists())
  file.createnewfile();
  string string="test zip!";
  byte[] buffer =string.getbytes();
  fileoutputstream foutputstream = new fileoutputstream(file);
  zipoutputstream zoutput = new zipoutputstream(foutputstream);
  zipentry zentry = new zipentry("test.txt");
  zoutput.putnextentry(zentry);
  zoutput.write(buffer);
  zoutput.closeentry();
  zoutput.close();
 }
}

补充:下面看下java中创建zip文件,并向zip文件中写入并读取条目和数据

package file;
 import java.io.file;
 import java.io.fileinputstream;
 import java.io.fileoutputstream;
 import java.io.ioexception;
 import java.util.zip.zipentry;
 import java.util.zip.zipinputstream;
 import java.util.zip.zipoutputstream;
 public class zipdemo {
public static void main(string[] args) throws ioexception {
// todo auto-generated method stub
 file file = new file("test.zip");
 if(!file.exists())
 file.createnewfile();
 string string="my name is ysd!";
 byte[] buffer =string.getbytes();
 byte[] bufferinput =new byte[4096]; 
 fileoutputstream foutputstream = new fileoutputstream(file);
 zipoutputstream zoutput = new zipoutputstream(foutputstream);
 zipentry zentry = new zipentry("one.txt");
 zoutput.putnextentry(zentry);
 zoutput.write(buffer);
 zoutput.closeentry();
 zoutput.close();
 zipinputstream zinputstream = new zipinputstream(new fileinputstream(file));
 zipentry zipentry = null;
 while((zipentry=zinputstream.getnextentry()) != null)
 {
 system.out.println(zipentry.getname());
 zinputstream.read(bufferinput);
 system.out.println(new string(bufferinput));
 zinputstream.closeentry();
 }
 zinputstream.close();
}
 } 

总结

以上所述是小编给大家介绍的java中创建zip文件的方法,希望对大家有所帮助

上一篇:

下一篇: