【问题标题】:Files uploaded using Apache Common Net FTPClient.storeFileStream are corrupted使用 Apache Common Net FTPClient.storeFileStream 上传的文件已损坏
【发布时间】:2021-02-17 21:08:37
【问题描述】:

我编写了一个用于压缩数据库文件 (.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】:

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

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

    要完成文件传输,您必须调用completePendingCommand 并检查其返回值以验证成功。如果不这样做,后续命令可能会出现意外行为。

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 1970-01-01
      • 2013-10-24
      • 2023-03-20
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      相关资源
      最近更新 更多