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