如何通过FTP下载文本文件并将内容读取为字符串

时间:2012-07-25 16:40:12

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

这是前一个问题的回复(可能有点不清楚)。

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

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

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

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

3 个答案:

答案 0 :(得分:3)

不打算为您完成工作,但是一旦建立了连接,就可以调用retrieveFile并将其传递给OutputStream。你可以谷歌并找到其余的......

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

ByteArrayOutputStream

retrieveFile

答案 1 :(得分: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;
}

答案 2 :(得分:0)

您可以跳过下载到本地文件系统的操作,然后执行以下操作:

    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();
         }
    }