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

Java 如何通过FTP下载文本文件并将内容读取为字符串,java,android,ftp,apache-commons,apache-commons-net,Java,Android,Ftp,Apache Commons,Apache Commons Net,这是根据之前的一个问题(可能有点不清楚)改写的 我想通过FTP从远程服务器下载一个文本文件,将文本文件的内容读入字符串,然后丢弃该文件。我不需要实际保存文件 我正在使用Apache Commons库,因此我有: import org.apache.commons.net.ftp.FTPClient; 有谁能帮我一下,而不只是把我重定向到一个有很多可能答案的页面吗?通常我会留下一条评论,询问''。但现在我感觉更慷慨了:-) 给你: private void ftpDownload() {

这是根据之前的一个问题(可能有点不清楚)改写的

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

我正在使用Apache Commons库,因此我有:

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

有谁能帮我一下,而不只是把我重定向到一个有很多可能答案的页面吗?

通常我会留下一条评论,询问''。但现在我感觉更慷慨了:-)

给你:

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;
}
private void ftpDownload(){
FTPClient ftp=null;
试一试{
ftp=新的FTPClient();
ftp.connect(mServer);
试一试{
int reply=ftp.getReplyCode();
如果(!FTPReply.isPositiveCompletion(回复)){
抛出新异常(“连接失败:+ftp.getReplyString());
}
如果(!ftp.login(mUser,mPassword)){
抛出新异常(“登录失败:+ftp.getReplyString());
}
试一试{
ftp.enterLocalPassiveMode();
如果(!ftp.setFileType(ftp.BINARY\u FILE\u TYPE)){
Log.e(标记“设置二进制文件类型失败”);
}
传输文件(ftp);
}捕获(例外e){
可手持的(e);
}最后{
如果(!ftp.logout()){
Log.e(标记“注销失败”);
}
}
}捕获(例外e){
可手持的(e);
}最后{
ftp.disconnect();
}
}捕获(例外e){
可手持的(e);
}
}
私有无效传输文件(FTPClient ftp)引发异常{
long fileSize=getFileSize(ftp,mFilePath);
InputStream is=retrieveFileStream(ftp、mFilePath);
下载文件(is、缓冲区、文件大小);
is.close();
如果(!ftp.completePendingCommand()){
抛出新异常(“挂起的命令失败:+ftp.getReplyString());
}
}
私有InputStream retrieveFileStream(FTPClient ftp,字符串文件路径)
抛出异常{
InputStream=ftp.retrieveFileStream(文件路径);
int reply=ftp.getReplyCode();
如果(is==null
||(!FTPReply.ispositivepremial(答复)
&&!FTPReply.isPositiveCompletion(回复))){
抛出新异常(ftp.getReplyString());
}
回报是;
}
私有字节[]下载文件(InputStream为,长文件大小)
抛出异常{
字节[]缓冲区=新字节[文件大小];
if(is.read(buffer,0,buffer.length))=-1){
返回null;
}

return buffer;//通常我会留下一条评论询问“”。但现在我感觉更慷慨了:-)

给你:

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;
}
private void ftpDownload(){
FTPClient ftp=null;
试一试{
ftp=新的FTPClient();
ftp.connect(mServer);
试一试{
int reply=ftp.getReplyCode();
如果(!FTPReply.isPositiveCompletion(回复)){
抛出新异常(“连接失败:+ftp.getReplyString());
}
如果(!ftp.login(mUser,mPassword)){
抛出新异常(“登录失败:+ftp.getReplyString());
}
试一试{
ftp.enterLocalPassiveMode();
如果(!ftp.setFileType(ftp.BINARY\u FILE\u TYPE)){
Log.e(标记“设置二进制文件类型失败”);
}
传输文件(ftp);
}捕获(例外e){
可手持的(e);
}最后{
如果(!ftp.logout()){
Log.e(标记“注销失败”);
}
}
}捕获(例外e){
可手持的(e);
}最后{
ftp.disconnect();
}
}捕获(例外e){
可手持的(e);
}
}
私有无效传输文件(FTPClient ftp)引发异常{
long fileSize=getFileSize(ftp,mFilePath);
InputStream is=retrieveFileStream(ftp、mFilePath);
下载文件(is、缓冲区、文件大小);
is.close();
如果(!ftp.completePendingCommand()){
抛出新异常(“挂起的命令失败:+ftp.getReplyString());
}
}
私有InputStream retrieveFileStream(FTPClient ftp,字符串文件路径)
抛出异常{
InputStream=ftp.retrieveFileStream(文件路径);
int reply=ftp.getReplyCode();
如果(is==null
||(!FTPReply.ispositivepremial(答复)
&&!FTPReply.isPositiveCompletion(回复))){
抛出新异常(ftp.getReplyString());
}
回报是;
}
私有字节[]下载文件(InputStream为,长文件大小)
抛出异常{
字节[]缓冲区=新字节[文件大小];
if(is.read(buffer,0,buffer.length))=-1){
返回null;
}

return buffer;//不会帮你做这项工作,但是一旦你建立了连接,你就可以调用retrieveFile并向它传递一个OutputStream。你可以四处搜索并找到其余的

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

不打算为您做这项工作,但一旦您建立了连接,您可以调用retrieveFile并向其传递一个OutputStream。您可以在谷歌上搜索并找到其余的

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

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

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

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

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

来吧,伙计。这在javadocs中是正确的:来吧,伙计。这在javadocs中是正确的:duffymo-你会在互联网上的某个地方找到我对你建议的回应。来吧,伙计,只需谷歌一下!Dheera-一段极其冗长的代码,导致了太多错误,Eclipse崩溃在我身上。有谁能给我一个更有用的解决方案吗?@Kevmeister你真的希望人们为你的项目提供一个工作解决方案吗?那么StackOverflow就不是这个地方了。这段代码是从我的项目中剥离出来的