簡體   English   中英

使用 Apache Common Net FTPClient.storeFileStream 上傳的文件已損壞

[英]Files uploaded using Apache Common Net FTPClient.storeFileStream are corrupted

我編寫了一個用於壓縮數據庫文件 (.zip) 並上傳到 FTP 服務器的代碼。 當我從服務器下載該文件時,文件已損壞。 原因是什么?

代碼:

FTPClient ftpClient = new FTPClient();      

ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);                 
  
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd");  
LocalDateTime now = LocalDateTime.now(); 
String currentDate = dtf.format(now);
         
String srcFilename = file;

String remoteFile = "STORE_" + currentDate + ".zip";
       
try {
    byte[] buffer = new byte[1024];
    OutputStream fos = ftpClient.storeFileStream(remoteFile);
    try (ZipOutputStream zos = new ZipOutputStream(fos)) {
        File srcFile = new File(srcFilename);
        try (FileInputStream fis = new FileInputStream(srcFile)) {
            zos.putNextEntry(new ZipEntry(srcFile.getName()));
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
        }
    }
}
catch (IOException ioe) {
    System.out.println("Error creating zip file" + ioe);
}

if (ftpClient.isConnected()) {
        ftpClient.logout();
        ftpClient.disconnect();
}

FTPClient.storeFileStream方法發起的文件上傳必須通過關閉流並調用FTPClient.completePendingCommand來完成:

完成寫入后,您必須關閉 OutputStream。 OutputStream 本身將在關閉時負責關閉父數據連接套接字。

要完成文件傳輸,您必須調用completePendingCommand並檢查其返回值以驗證成功。 如果不這樣做,后續命令的行為可能會出乎意料。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM