2012-04-11 2 views
1

일부 파일을 ZIP 파일에 추가하려고하지만 파일을 생성하지만 아무것도 추가하지 않습니다. 코드 1 :ZIP 파일에 파일 추가

String fulldate = year + "-" + month + "-" + day + "-" + min; 

File dateFolder = new File("F:\\" + compname + "\\" + fulldate); 
dateFolder.mkdir(); 

String zipName = "F:\\" + compname + "\\" + fulldate + "\\" + fulldate + ".zip"; 

zipFolder(tobackup, zipName); 

내 기능 :

public static void zipFolder(File folder, String name) throws Exception { 
    byte[] buffer = new byte[18024]; 

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(name)); 
    FileInputStream in = new FileInputStream(folder); 

    out.putNextEntry(new ZipEntry(name)); 

    int len; 

    while((len = in.read(buffer)) > 0) { 
     out.write(buffer, 0, len); 
    } 

    out.closeEntry(); 
    in.close(); 
    out.close(); 
} 

편집 : 내가, 그것을 그냥 C에서 문제 기록 파일을 가지고 있던 문제가 발견 : \은 F에 우편으로 드라이브 : \ drive

+0

당신이 주어진 폴더에있는 파일을 반복에서 ['때 listFiles를 사용하려는 경우()'-method] (http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles())를 참조하십시오. –

답변

14

폴더 만 압축 할 수는 없습니다. 폴더를 압축하려면 모든 하위 파일을 수동으로 추가해야합니다. 나는이 일을하는이 수업을 썼다. 당신은 사용법이 될 것이다 무료 :

을 위해 그것을 할 수 있습니다 :

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.List; 
import java.util.zip.Deflater; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 

public class Packager 
{ 
    public static void packZip(File output, List<File> sources) throws IOException 
    { 
     System.out.println("Packaging to " + output.getName()); 
     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output)); 
     zipOut.setLevel(Deflater.DEFAULT_COMPRESSION); 

     for (File source : sources) 
     { 
      if (source.isDirectory()) 
      { 
       zipDir(zipOut, "", source); 
      } else 
      { 
       zipFile(zipOut, "", source); 
      } 
     } 
     zipOut.flush(); 
     zipOut.close(); 
     System.out.println("Done"); 
    } 

    private static String buildPath(String path, String file) 
    { 
     if (path == null || path.isEmpty()) 
     { 
      return file; 
     } else 
     { 
      return path + "/" + file; 
     } 
    } 

    private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException 
    { 
     if (!dir.canRead()) 
     { 
      System.out.println("Cannot read " + dir.getCanonicalPath() + " (maybe because of permissions)"); 
      return; 
     } 

     File[] files = dir.listFiles(); 
     path = buildPath(path, dir.getName()); 
     System.out.println("Adding Directory " + path); 

     for (File source : files) 
     { 
      if (source.isDirectory()) 
      { 
       zipDir(zos, path, source); 
      } else 
      { 
       zipFile(zos, path, source); 
      } 
     } 

     System.out.println("Leaving Directory " + path); 
    } 

    private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException 
    { 
     if (!file.canRead()) 
     { 
      System.out.println("Cannot read " + file.getCanonicalPath() + " (maybe because of permissions)"); 
      return; 
     } 

     System.out.println("Compressing " + file.getName()); 
     zos.putNextEntry(new ZipEntry(buildPath(path, file.getName()))); 

     FileInputStream fis = new FileInputStream(file); 

     byte[] buffer = new byte[4092]; 
     int byteCount = 0; 
     while ((byteCount = fis.read(buffer)) != -1) 
     { 
      zos.write(buffer, 0, byteCount); 
      System.out.print('.'); 
      System.out.flush(); 
     } 
     System.out.println(); 

     fis.close(); 
     zos.closeEntry(); 
    } 
} 

즐기십시오 :

여기
List<File> sources = new ArrayList<File>(); 
sources.add(tobackup); 
Packager.packZip(new File(zipName), sources); 

클래스입니다!

편집 : 프로그램이 여전히 사용중인 경우 당신이 내가 표시된 세 줄을 추가 할 수 있습니다, 확인하는 (*)

편집 2 : 새 코드를 사용해보십시오. 내 플랫폼에서 올바르게 실행됩니다 (OS X). 확실치 않지만 AppData의 Windows 파일에 대한 읽기 권한이 제한적일 수 있습니다.

+0

고마워! 나는 그것이 어떻게되는지 보자! 편집 : 그것은 잘 보였다, 그것을 압축 (: D 조),하지만 그것은 분명히 잘못되었습니다. 오류 : 압축 (압축) 폴더 'F : \ David-PC \ 2012-03-11-25 \ 2012-03-11-25.zip'이 잘못되었습니다. – cheese5505

+0

잠깐 - 이상하게. 아무런 이유없이 자동으로 종료되었습니다. "끝난." 나타나지 않았다. – cheese5505

+1

+1 좋은 친구 야! – GingerHead

2

ZeroTurnaround's Zip library도 참조하십시오. 그것은 (인용)과 같은 기능을 가지고 있습니다 :

  • 팩과 디렉토리를 풀고 재귀
  • ZIP 항목을 통해
  • 으로 반복