实现RETR FTP命令Java

时间:2015-11-11 21:17:43

标签: java ftp

您好我正在尝试实现RETR FTP命令,以便从远程服务器下载文件。我在FTP被动模式下这样做。我面临的问题是,在发出RETR命令后,我从服务器得到响应,如下所示:

2015/11/11 23:08:11: >RETR /pub/site/README
2015/11/11 23:08:13: <150 Opening BINARY mode data connection for /pub/site/README (175 bytes).

这是正常的,正是我期望得到的。在此之后,虽然不是文件下载,但我得到的只是IOException。我不知道问题是什么。有人可以帮忙吗?以下是实现RETR命令的方法:

public synchronized boolean retr(String fileName) throws IOException {

        Trace.connection = true;
        String response = null;

        if(!isBinary && !isPassive){
            passv();
        }

        String fullPath = pwd() + "/" + fileName;
        Trace.trc("Will retrieve the following file: " + fullPath);

        sendLine("RETR " + fullPath);
        response = readLine();
        if(!response.startsWith("150")){
            throw new IOException("Unable to download file from the remote server");
        }   

        BufferedInputStream input = new BufferedInputStream(dataSocket.getInputStream());
        BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(fileName)));

        byte[] buffer = new byte[4096];
        int bytesRead = 0;

        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(bytesRead);
        }
        output.close();
        input.close();

        if(response.startsWith("226")){
            isPassive = false;
            return true;
        }else{
            throw new IOException("Error");
        }
    }

以下是我得到的例外情况:

java.io.IOException: Error
    at connectors.FtpConnection.retr(FtpConnection.java:275)
    at ui.FtpDialog.fileDlBtActionPerformed(FtpDialog.java:339)
    at ui.FtpDialog.access$300(FtpDialog.java:23)
    at ui.FtpDialog$4.actionPerformed(FtpDialog.java:178)

2 个答案:

答案 0 :(得分:0)

您需要检查您的代码:

    if(response.startsWith("226")){
        isPassive = false;
        return true;
    }else{
        throw new IOException("Error");
    }

显然,你抛出一个IOException,因为你的响应以“150”开头,而不是“226”

150 Opening BINARY mode data connection for /pub/site/README (175 bytes).

答案 1 :(得分:0)

你在这里检查了什么:

sendLine("RETR " + fullPath);
response = readLine();
if(!response.startsWith("150")){
throw new IOException("Unable to download file from the remote server");
}

正如您所看到的,发出RETR命令的响应确实是“150”,然后代码继续执行从服务器下载文件的工作。您提到的部分代码的作用是检查“226”回复,表示所有内容都已正确完成。据我所知,问题是文件永远不会被实际下载。