【问题标题】:How to download a text file via FTP and read the contents to a string如何通过 FTP 下载文本文件并将内容读入字符串
【发布时间】:2012-07-24 04:04:54
【问题描述】:

这是从上一个问题中重新措辞的(可能有点不清楚)。

我想通过 FTP 从远程服务器下载文本文件,将文本文件的内容读入字符串,然后丢弃该文件。我不需要实际保存文件。

我正在使用 Apache Commons 库,所以我有:

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

谁能帮忙,而不是简单地将我重定向到一个有很多可能答案的页面?

【问题讨论】:

标签: java android ftp apache-commons apache-commons-net


【解决方案1】:

不会为您完成这项工作,但是一旦您建立了连接,您就可以调用retrieveFile 并将其传递给OutputStream。你可以google一下,找到剩下的……

 FTPClient ftp = new FTPClient();
 ...
 ByteArrayOutputStream myVar = new ByteArrayOutputStream();
 ftp.retrieveFile("remoteFileName.txt", myVar);

ByteArrayOutputStream

retrieveFile

【讨论】:

  • 谢谢迈克。今天用完了,所以我明天(或后天)将尝试解决剩下的难题。
  • @Kevmeister 您忘记将此标记为您问题的答案。
【解决方案2】:

通常我会留下评论询问“What have you tried?”。但现在我感觉更慷慨了:-)

给你:

private void ftpDownload() {
    FTPClient ftp = null;
    try {
        ftp = new FTPClient();
        ftp.connect(mServer);

        try {
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new Exception("Connect failed: " + ftp.getReplyString());
            }
            if (!ftp.login(mUser, mPassword)) {
                throw new Exception("Login failed: " + ftp.getReplyString());
            }
            try {
                ftp.enterLocalPassiveMode();
                if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
                    Log.e(TAG, "Setting binary file type failed.");
                }
                transferFile(ftp);
            } catch(Exception e) {
                handleThrowable(e);
            } finally {
                if (!ftp.logout()) {
                    Log.e(TAG, "Logout failed.");
                }
            }
        } catch(Exception e) {
            handleThrowable(e);
        } finally {
            ftp.disconnect();
        }
    } catch(Exception e) {
        handleThrowable(e);
    }
}

private void transferFile(FTPClient ftp) throws Exception {
    long fileSize = getFileSize(ftp, mFilePath);
    InputStream is = retrieveFileStream(ftp, mFilePath);
    downloadFile(is, buffer, fileSize);
    is.close();

    if (!ftp.completePendingCommand()) {
        throw new Exception("Pending command failed: " + ftp.getReplyString());
    }
}

private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
    InputStream is = ftp.retrieveFileStream(filePath);
    int reply = ftp.getReplyCode();
    if (is == null
            || (!FTPReply.isPositivePreliminary(reply)
                    && !FTPReply.isPositiveCompletion(reply))) {
        throw new Exception(ftp.getReplyString());
    }
    return is;
}

private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
    byte[] buffer = new byte[fileSize];
    if (is.read(buffer, 0, buffer.length)) == -1) {
        return null;
    }
    return buffer; // <-- Here is your file's contents !!!
}

private long getFileSize(FTPClient ftp, String filePath) throws Exception {
    long fileSize = 0;
    FTPFile[] files = ftp.listFiles(filePath);
    if (files.length == 1 && files[0].isFile()) {
        fileSize = files[0].getSize();
    }
    Log.i(TAG, "File size = " + fileSize);
    return fileSize;
}

【讨论】:

  • duffymo - 您可以在 Internet 上的某个地方找到我对您建议的回复。来吧,谷歌吧!
  • Dheera - 一段极其冗长的代码导致了太多错误,以至于 Eclipse 崩溃了。
  • 谁能给我一个更有帮助的解决方案?
  • @Kevmeister 你真的希望人们为你的项目提供一个可行的解决方案吗?然后 StackOverflow 不适合它。这段代码是从我的项目中删除不相关的代码部分后提取的。所以它当然不会编译。尝试理解它并根据需要调整代码。
  • 不,我不希望这样,但我也不希望一大堆未注释的代码扔给我。我需要帮助,而不是来自糟糕的论坛版主的菜鸟抨击。
【解决方案3】:

您可以跳过下载到本地文件系统部分并执行以下操作:

    FTPClient ftpClient = new FTPClient();
    try {
       ftpClient.connect(server, port);
       ftpClient.login(user, pass);
       ftpClient.enterLocalPassiveMode();
       ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

       InputStream inputStream = ftpClient.retrieveFileStream("/folder/file.dat");
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "Cp1252"));

       while(reader.ready()) {
           System.out.println(reader.readLine()); // Or whatever
       }
       inputStream.close();

    } catch (IOException ex) {
         ex.printStackTrace();
    } finally {
         try {
             if (ftpClient.isConnected()) {
                 ftpClient.logout();
                 ftpClient.disconnect();
             }
         } catch (IOException ex) {
               ex.printStackTrace();
         }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多