2012-06-16 6 views
-2
<% // Set the content type based to zip 
    response.setContentType("Content-type:text/zip"); 
    response.setHeader("Content-Disposition", "attachment; filename=mytest.zip"); 

    // List of files to be downloaded 
    List files = new ArrayList(); 
    files.add(new File("C:/first.txt")); 
    files.add(new File("C:/second.txt")); 
    files.add(new File("C:/third.txt")); 

    ServletOutputStream out1 = response.getOutputStream(); 
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out1)); 
    for (Object file : files) 
    { 
     //System.out.println("Adding file " + file.getName()); 
     System.out.println("Adding file " + file.getClass().getName()); 
     //zos.putNextEntry(new ZipEntry(file.getName())); 
     zos.putNextEntry(new ZipEntry(file.getClass().getName())); 
     // Get the file 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(file); 
     } catch (Exception E) { 
      // If the file does not exists, write an error entry instead of file contents 
      //zos.write(("ERROR: Could not find file " + file.getName()).getBytes()); 
      zos.write(("ERROR: Could not find file" +file.getClass().getName()).getBytes()); 
      zos.closeEntry(); 
      //System.out.println("Could not find file "+ file.getAbsolutePath()); 
      continue; 
     } 
     BufferedInputStream fif = new BufferedInputStream(fis); 
     // Write the contents of the file 
     int data = 0; 
     while ((data = fif.read()) != -1) { 
      zos.write(data); 
     } 
     fif.close(); 
     zos.closeEntry(); 
     //System.out.println("Finished adding file " + file.getName()); 
     System.out.println("Finished adding file " + file.getClass().getName()); 
    } 
    zos.close(); 
%> 

이 내 actualy 프로그램은, 당신이 나를 도울 수, JAVA 프로그래밍에 새로운 오전, 와트 내가이 방법은 오른쪽 또는 잘못하고있는 중이 야되는 여러 개의 파일을 압축하려면 다음을 다운로드한다 ???여러 개의 파일을 하나의 zip으로 선택하고 zip 파일을 다운로드 할 때 오류가 있습니까?

+0

또한'files' 컬렉션을 채우는 코드를 게시해야합니다. 어떤 종류의 물체가 안에 있는지 알면 도움이됩니다. – npe

답변

0

귀하의 for 루프는 다음과 같아야합니다

for (File file : files) { 
    ... 

또는

for (String file : files) { 
    ... 

당신이 file 변수를 선언하는 방법은, 컴파일러가이 Object, 아닌 File 인스턴스의 가정합니다. 따라서 Object을 수락하는 FileInputStream 생성자가 없으므로 컴파일 오류가 발생합니다. file은 파일의 절대 경로를 포함하는 File 또는 String이어야합니다.

또 다른 오류는 파일 이름을 ZipEntry에 전달하는 것입니다. 사용 :

file.getClass().getName() 

"java.io.File" 또는 "java.lang.String", 그리고 파일 이름에 발생합니다. 파일의 적절한 이름을 설정하려면 File#getName()을 사용하십시오.

관련 문제