2013-06-28 54 views
0

我要上傳一個zip文件到ftp服務器,並且這裏的zip文件也是動態構建的。錯誤在ZipOutputStream + FTPClient

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.util.zip.ZipOutputStream; 

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; 
import org.apache.commons.io.IOUtils; 
import org.apache.commons.net.ftp.FTPClient; 

public class CommonsNet { 
    public static void main(String[] args) throws Exception { 
     FTPClient client = new FTPClient(); 
     FileInputStream fis = null; 
     try { 
      client.connect("127.0.0.1"); 
      client.login("phani", "phani"); 
      String filename = "D://junk.pdf"; 
      fis = new FileInputStream(new File(filename)); 
      byte[] bs = IOUtils.toByteArray(fis); 
      fis.close(); 
      OutputStream outputStream = client.storeFileStream("remote.zip"); 

      ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); 

      zipOutputStream.setLevel(ZipOutputStream.STORED); 
      addOneFileToZipArchive(zipOutputStream, 
        "junk.pdf", bs); 
      zipOutputStream.close(); 

      outputStream.close(); 

      client.logout(); 
      System.out.println("Transfer done"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fis != null) { 
        fis.close(); 
       } 
       client.disconnect(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void addOneFileToZipArchive(ZipOutputStream zipStream, 
      String fileName, byte[] content) throws Exception { 
     ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName); 
     zipStream.putNextEntry(zipEntry); 
     zipStream.write(content); 
     zipStream.flush(); 
     zipStream.closeEntry(); 
    } 
} 

執行此代碼後,該文件已成功創建,但我無法在歸檔中打開文件。 像:

! D:\phani\remote.zip: The archive is corrupt 
! D:\phani\remote.zip: Checksum error in C:\Users\BHAVIR~1.KUM\AppData\Local\Temp\Rar$DIa0.489\MCReport.pdf. The file is corrupt 
+0

我嘗試了一種方式,首先我在本地服務器(工作正常)創建一個zip文件,然後我使用下面的代碼保存在webserver中:fis = new FileInputStream(「D://local.zip」); \t \t \t client.storeFile(「dump.zip」,fis);仍然我無法打開文件裏面的文件 –

回答

1

嘗試增加client.setFileType(FTP.BINARY_FILE_TYPE);您在登錄後立即

我記得,默認傳輸模式爲ASCII,因此非ASCII文件可能會導致損壞。

+0

謝謝,它的工作,早些時候我用FTPClient.BINARY_FILE_TYPE作爲fileType。爲什麼FTPClient.BINARY_FILE_TYPE無法正常工作。 –