使用 Apache Common Net FTPClient.storeFileStream 上传的文件已损坏

问题描述 投票:0回答:1

我编写了一个用于压缩数据库文件(.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();
}
java ftp upload apache-commons-net
1个回答
0
投票

FTPClient.storeFileStream
方法发起的文件上传必须通过关闭流并调用 FTPClient.completePendingCommand
:
来完成

写入完毕后必须关闭 OutputStream。 OutputStream 本身将在关闭时负责关闭父数据连接套接字。

要完成文件传输,您必须调用 completePendingCommand

 并检查其返回值以验证是否成功。 如果不这样做,后续命令可能会出现意外行为。

© www.soinside.com 2019 - 2024. All rights reserved.