【问题标题】:Implementing the RETR FTP command Java实现 RETR FTP 命令 Java
【发布时间】:2015-11-11 21:17:43
【问题描述】:

您好,我正在尝试执行 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)

【问题讨论】:

  • 我想,你需要检查一下,FtpConnection.java 第 275 行、FtpDialog.java 第 339 行、FtpDialog.java 第 23 行和 FtpDialog.java 第 178 行有什么。
  • 第 275 行是方法的结尾。第 339 行是调用该方法的位置。所以那里没有问题。问题出在其他地方。

标签: java ftp


【解决方案1】:

您需要检查您的代码:

    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).

【讨论】:

    【解决方案2】:

    您提到的内容在此处检查:

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

    如您所见,如果发出 RETR 命令的响应确实是“150”,那么代码会继续执行它的工作,即从服务器下载文件。您提到的部分代码的作用是检查“226”回复,这表示一切都已正确完成。据我所知,问题在于该文件从未真正下载过。

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多