Howto do a simple ftp get file on Android

送分小仙女□ 提交于 2019-11-27 01:48:13

Whew! I finally got it going. I gave up on the simple way that works in webOS and WPF/C# where you can just do a ftp:://... you have to use the FTPClient package.

After fixing the library access (Project | Properties | Java Build Path | Libraries | Add JARs...) I fiddled with the calls until it started working. Here's the sequence of my FTPClient calls. It wouldn't work until I set it in passive mode.

  mFTPClient = new FTPClient();
  mFTPClient.connect("tgftp.nws.noaa.gov");      
  mFTPClient.login("anonymous","nobody");
  mFTPClient.enterLocalPassiveMode();
  mFTPClient.changeWorkingDirectory("/data/forecasts/taf/stations");
  InputStream inStream = mFTPClient.retrieveFileStream("KABQ.TXT");
  InputStreamReader isr = new InputStreamReader(inStream, "UTF8");

And I also found on the web someplace an answer to the 'byte-by-byte' question. This seems to work to convert an InputStream type directly to String type:

      String theStr = new Scanner(inStream).useDelimiter("\\A").next();

I also looked for a simple ftp download example without using of 3rd party libs. Didn't find any, so post my solution here.

URLConnection by default uses user name 'anonymous' with empty password which is not accepted by many ftp servers, as they require e-mail as the password for 'anonymous'.

To use the following code in your app, just add try..catch and make sure that reading from stream isn't block UI thread.

URL url = new URL("ftp://ftp.mozilla.org/README");
URLConnection cn = url.openConnection();
cn.setRequestProperty ("Authorization", "Basic " + Base64.encodeToString("anonymous:a@b.c".getBytes(), Base64.DEFAULT));

final File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
FileOutputStream fos = new FileOutputStream(dir.getPath() + "/README");

InputStream is = cn.getInputStream();
int bytesRead = -1;
byte[] buf = new byte[8096];
while ((bytesRead = is.read(buf)) != -1) {
    fos.write(buf, 0, bytesRead);
}
if(is != null)is.close();
if(fos != null){ fos.flush(); fos.close(); }

Hope this will save you some time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!