Java中创建ZIP文件的方法
java创建zip文件的代码如下如下:
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipInputStream;
importjava.util.zip.ZipOutputStream;
publicclassZipDemo{
publicstaticvoidmain(String[]args)throwsIOException{
Filefile=newFile("test.zip");
if(!file.exists())
file.createNewFile();
Stringstring="testZIP!";
byte[]buffer=string.getBytes();
FileOutputStreamfOutputStream=newFileOutputStream(file);
ZipOutputStreamzoutput=newZipOutputStream(fOutputStream);
ZipEntryzEntry=newZipEntry("test.txt");
zoutput.putNextEntry(zEntry);
zoutput.write(buffer);
zoutput.closeEntry();
zoutput.close();
}
}
补充:下面看下JAVA中创建ZIP文件,并向ZIP文件中写入并读取条目和数据
packageFile;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipInputStream;
importjava.util.zip.ZipOutputStream;
publicclassZipDemo{
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
Filefile=newFile("test.zip");
if(!file.exists())
file.createNewFile();
Stringstring="mynameisysd!";
byte[]buffer=string.getBytes();
byte[]BufferInput=newbyte[4096];
FileOutputStreamfOutputStream=newFileOutputStream(file);
ZipOutputStreamzoutput=newZipOutputStream(fOutputStream);
ZipEntryzEntry=newZipEntry("one.txt");
zoutput.putNextEntry(zEntry);
zoutput.write(buffer);
zoutput.closeEntry();
zoutput.close();
ZipInputStreamzInputStream=newZipInputStream(newFileInputStream(file));
ZipEntryzipEntry=null;
while((zipEntry=zInputStream.getNextEntry())!=null)
{
System.out.println(zipEntry.getName());
zInputStream.read(BufferInput);
System.out.println(newString(BufferInput));
zInputStream.closeEntry();
}
zInputStream.close();
}
}
总结
以上所述是小编给大家介绍的Java中创建ZIP文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!