java生成zip包简单实现
简单实现java压缩文件功能,希望对初学者有所帮助。废话不多说,直接看代码。
代码如下:
public static void main(String[] args) throws Exception {File file = new File("d:/a.txt");// 1.拿到文件的输入流InputStream is = new FileInputStream(file);// 2.创建zip文件输出流ZipOutputStream os = new ZipOutputStream(new FileOutputStream(file.getAbsolutePath() + ".zip"));os.setLevel(9);// 压缩率设置最高// 设置要写入的 ZIP 条目os.putNextEntry(new ZipEntry(file.getName()));byte[] bytes = new byte[32 * 1024];int len = -1;while((len = is.read(bytes)) > 0) {os.write(bytes, 0, len);}// closeos.closeEntry();os.close();// 如果少了这句,压缩包无法打开is.close();}