FTP 下载期间正在创建新文件

New file is getting created during FTP download

我正在尝试使用 FTP 从服务器下载文件,如果文件在远程服务器中可用,但如果特定文件在远程服务器中不可用,则 Java 代码有效正在本地创建一个具有相同文件名的新文件。我怎样才能避免这种情况?

并且我试图在下载之前检查特定文件的属性,例如上次修改时间、文件创建时间等。我使用了 MLST,但遇到了类型转换问题..!!

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FTPDownloadFileDemo {

public static void main(String[] args) {
    String server = "www.myserver.com";
    int port = 21;
    String user = "user";
    String pass = "pass";

    FTPClient ftpClient = new FTPClient();
    try {

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

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String remoteFile1 = "/test/video.mp4";
        File downloadFile1 = new File("D:/Downloads/video.mp4");
        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
        boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

        if (success) {
            System.out.println("File #1 has been downloaded successfully.");
        }

        outputStream2.close();
        inputStream.close();

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

}

你的问题是你的 Outputstream 自动创建文件,即使流是空的。

我建议您先检查服务器上是否存在该文件,基于此您甚至不创建 outputStream:

boolean checkFileExists(String filePath) throws IOException {
    InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
    returnCode = ftpClient.getReplyCode();
    return inputStream == null || returnCode == 550;
}

retrieveFile() 方法总是写入本地文件,无论远程文件是否存在。相反,您可以使用 retrieveFileStream() 并检查回复代码。

A handy list of FTP reply codes 可从维基百科获得。如果收到 550,则表示该文件不存在。

最后,您需要使用completePendingCommand() to complete the transaction and a FileOutputStream写入文件。

InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
int returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
    System.out.println("Remote file does not exist");
} else {
    ftpClient.completePendingCommand();
    byte[] buffer = new byte[inputStream.available()];
    inputStream.read(buffer);
    OutputStream outputStream = new FileOutputStream(downloadFile1);
    outputStream.write(buffer);
    outputStream.close();
}