2012-06-16 65 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(); 
%> 

这是我的实际程序,想压缩多个文件,然后下载它,是我正在做的方式是正确的或错误的,是新的JAVA编程,你能帮我吗?将多个文件选择到一个zip文件并下载zip文件时出错?

+0

您还应该发布填充'files'集合的代码。这将有助于了解内部是什么类型的对象。 – npe

回答

0

for循环应该是这样的:

for (File file : files) { 
    ... 

for (String file : files) { 
    ... 

你声明file变量的方式,使编译器假定它是一个Object,而不是一个File实例。因此,您会收到编译错误,因为没有FileInputStream构造函数接受Objectfile必须是包含文件绝对路径的FileString

另一个错误就是你将文件名传递给ZipEntry。 使用:

file.getClass().getName() 

将导致"java.io.File""java.lang.String",而不是文件名。 要设置文件的正确名称,请使用File#getName()