Skip to content Skip to sidebar Skip to footer

Reading Txt File From An Ftp Server And Returning It From Asynctask

I have a txt file in my ftp server. And all I want to do is reading that file, retrieve the contents and save it as a string by using AsyncTask. As I understand from the logcat, I'

Solution 1:

Your code must be like :

package com.example.ftpdenemeleri;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPCmd;
import android.os.AsyncTask;

publicclassFtpAsyncextendsAsyncTask <Void, Void, String>{

@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();      
}

@Overrideprotected String doInBackground(Void... params) {
// TODO Auto-generated method stubFTPClientftpClient=newFTPClient();
try {
    ftpClient.connect("hostname", 21);

    System.out.println(ftpClient.getReplyString());
    ftpClient.sendCommand(FTPCmd.USER, "user");
    System.out.println(ftpClient.getReplyString());
    ftpClient.sendCommand(FTPCmd.PASS, "pass");
    System.out.println(ftpClient.getReplyString());
    ftpClient.sendCommand(FTPCmd.CWD, "/home/www/bitirme");
    InputStreamis=newBufferedInputStream(ftpClient.retrieveFileStream("beaglesays.txt")); 
    System.out.println("Input Stream has opened.");

Scanners=newScanner(is).useDelimiter("\\A"); // Convert your stream into stringreturn s.hasNext() ? s.next() : ""; //send the string to onPostExecute()


  } catch (IOException ex) {
    System.err.println(ex);
}
returnnull; 
}


protectedvoidonPostExecute(String result) {
    // TODO: check this.exception // TODO: do something with the feed
Log.i("Result : ",result);
    }
}

Solution 2:

There are many ways to fully read an InputStream into a String. The easiest one would be to use IOUtils.toString() from Apache Commons IO.

So, assuming that, the changes would be to return said string from doInBackground() and receive it in onPostExecute().

Solution 3:

Try to understand AsyncTask clearly. Few things: (1) Similar question: Howto do a simple ftp get file on Android (2) Once you get content in doInBackground() - return the content as String(at present you are returning null). (3) Add parameter in onPostExecute(String result) and this will the content of the file.

Post a Comment for "Reading Txt File From An Ftp Server And Returning It From Asynctask"