FTP下载期间将创建新文件

时间:2018-02-06 23:01:15

标签: java ftp ftp-client

我尝试使用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();
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

您的问题是您的Outputstream会自动创建文件,即使该流为空。

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

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

答案 1 :(得分:1)

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

维基百科提供handy list of FTP reply codes。如果收到550,则表示该文件不存在。

最后,您需要使用completePendingCommand()来完成事务,并使用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();
}