ساخت فایل zip در داخل برنامه جاوا zip file build in java adf
از کد زیر میتوانید برای ساخت فایل zip استفاده نمایید.
package test;</p> <p>import java.io.File;<br /> import java.io.FileInputStream;<br /> import java.io.FileNotFoundException;<br /> import java.io.FileOutputStream;<br /> import java.io.IOException;<br /> import java.util.zip.ZipEntry;<br /> import java.util.zip.ZipOutputStream;</p> <p>public class ZipFiles {</p> <p>public static void main(String[] args) {</p> <p>try {<br /> FileOutputStream fos = new FileOutputStream("atest.zip");<br /> ZipOutputStream zos = new ZipOutputStream(fos);</p> <p>String file1Name = "file1.txt";<br /> String file2Name = "file2.txt";<br /> String file3Name = "folder/file3.txt";<br /> String file4Name = "folder/file4.txt";<br /> String file5Name = "f1/f2/f3/file5.txt";</p> <p>addToZipFile(file1Name, zos);<br /> addToZipFile(file2Name, zos);<br /> addToZipFile(file3Name, zos);<br /> addToZipFile(file4Name, zos);<br /> addToZipFile(file5Name, zos);</p> <p>zos.close();<br /> fos.close();</p> <p>} catch (FileNotFoundException e) {<br /> e.printStackTrace();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }</p> <p>}</p> <p>public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {</p> <p>System.out.println("Writing '" + fileName + "' to zip file");</p> <p>File file = new File(fileName);<br /> FileInputStream fis = new FileInputStream(file);<br /> ZipEntry zipEntry = new ZipEntry(fileName);<br /> zos.putNextEntry(zipEntry);</p> <p>byte[] bytes = new byte[1024];<br /> int length;<br /> while ((length = fis.read(bytes)) >= 0) {<br /> zos.write(bytes, 0, length);<br /> }</p> <p>zos.closeEntry();<br /> fis.close();<br /> }</p> <p>}