试图让我的Android应用程序将文件放在我的ftp服务器上

时间:2011-08-04 23:28:44

标签: android ftp apache-commons

我花了很多时间尝试使这段代码工作,并且在当前状态下它几乎完全反映了我在https://stackoverflow.com/questions/3482583/apache-ftpclient-failing-to-download-larger-files找到的代码。我也在使用apache commons net。 由于某种原因,我的应用程序永远不会通过client.connect步骤,即使我插入应该工作的ftp服务器的其他IP地址。

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.*;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;



public class FtpClientService extends Activity {
    //static int fail;


 public FtpClientService(){  
 }


 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.ftp);
    FtpConnect();
}

public static void FtpConnect(){
  String userName="usrname";
  String passWord = "password";
  String ftpAddress = "127.0.0.1"; //this isnt the ip address I was using...
  String retrieveFromFTPFolder = "/Pictures/";
  String strLine;
  DataInputStream inputStream = null;
  BufferedReader bufferedReader = null;
  FTPClient client = null;
  FTPFile[] ftpFiles = null;
  int reply;

  try{

      client = new FTPClient();
   client.setListHiddenFiles(true);
   client.connect(ftpAddress); //this right here is where it fails
   client.login(userName, passWord);
   client.setFileType(FTP.BINARY_FILE_TYPE);
      if(!client.completePendingCommand()) {
          client.logout();
          client.disconnect();
          System.err.println("File transfer failed.");

      }

  } catch (Exception e) {
   if (client.isConnected()) {
    try {
     client.logout();  
     client.disconnect();  
    } 
    catch (IOException f) {}
   }
  }
  finally{
   if (client.isConnected()) {
    try {
     client.logout();
     client.disconnect();
    }
    catch (IOException f){}
   }
  }  
 }

 public static void main(String[] args) {
  FtpConnect();
 }

提前致谢!

2 个答案:

答案 0 :(得分:0)

connect方法中,将带有适当地址和端口的构造InetAddress传递给它。

另外,不要在主线程上执行FTP连接,请考虑使用AsyncTask

答案 1 :(得分:0)

尝试使用:

client.connect(InetAddress.getByAddress(ftpAddress,new byte[]{127,0,0,1}));