本帖最后由 刘丁 于 2012-2-20 09:41 编辑
- package com.koal.demo.Interview;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- public class ZipOutputStreamDemo {
- public static void main(String[] args) throws Exception{
- File f1 = new File("E:\\Java基础加强.ppt");
- File f2 = null;
- String fileName = f1.getName();
-
- f2 = f1.isDirectory() ? new File(f1.getParent() + f1.getName() + ".zip") :
- new File(f1.getParent() + fileName.substring(0, fileName.lastIndexOf('.')) + ".zip");
- InputStream in = null;
- ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f2));
- List<String> list = new ArrayList<String>();
- test(f1, list);
- byte[] buf = new byte[1024];
- int len = 0;
- for (String s : list) {
- out.putNextEntry(new ZipEntry(s.substring(s.indexOf(fileName))));
- in = new FileInputStream(new File(s));
- while ((len = in.read(buf)) != -1) {
- out.write(buf, 0, len);
- }
- }
- in.close();
- out.close();
- System.out.println("压缩完成");
- }
-
- public static void test(File file, List<String> list) {
- if (file.isDirectory()) {
- File[] files = file.listFiles();
- for (File file2 : files) {
- test(file2, list);
- }
- }else {
- list.add(file.getPath());
- }
- }
- }
复制代码 文件名出现乱码,如何解决。 |
|