android 基于ftp远程文件管理


最近公司项目有关于一个远程文件管理内容,在网上查了查发现大部分是基于ftp来实现的,但是找了半天也没找到一个合适的例子,最后得到群里同学帮助下成功完成,

我对项目进行了简单的总结,供大家学习使用。


android端还需要引入第三方jar包的支持,才可实现,我这里选用的是apache官方的commons-net-3.2.jar,解压后导入jar包即可,已经上传

http://download.csdn.net/detail/yudajun/5140914


主要代码如下:


package com.ftpbrowser.sample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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.FTPReply;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FtpFileManage {
	private final String tag="fileManageLog";
	
	private final static String REFRESH_PATH = "start_path";
	private final static String CHANGE_FILE_PATH = "change_path";
	private final static String DELETE_FILE = "delete_file";
	private final static String UPLOAD_FILE = "upload_file";
	private final static String DOWNLOAD_FILE = "download_file";
	private final static String COPY_FILE = "copy_file";
	private final static String MOVE_FILE = "move_file";
	private final static String dirChar = File.separator;
	private static String FTP_DEFAULT_CODE = "ISO-8859-1";
	private final static String GBK = "GBK";
	private final static String UTF = "UTF-8";
	private final static String TEMP_FILE_DIR = FtpBrowserActivity2.STORE_DIRECTORY + "/_temp";
	
	private List<FtpFileInfo> mFilesInfo;
	private List<String> mStackNowPath;
	private List<FtpFileInfo> mCheck4Paste;
	private static FtpFileManage instance = null;  
    private static FTPClient ftpClient = null;
	FtpBrowserActivity2 browserActivity;
	
	private FtpFileManage(){
		mFilesInfo=new ArrayList<FtpFileInfo>();
		mStackNowPath=new ArrayList<String>();
		mCheck4Paste = new ArrayList<FtpFileInfo>();
		mStackNowPath.add(dirChar);
		ftpClient = new FTPClient();
		FTP_DEFAULT_CODE = ftpClient.getControlEncoding();
	}
	
	public static synchronized FtpFileManage getInstance(){
		if(null==instance){
			instance=new FtpFileManage();
		}
		return instance;
	}
	
	public void setActivity(){
		this.browserActivity=FtpBrowserActivity2.browserActivity;
	}
	/**
	 * 获取远程文件信息列表
	 * @return
	 */
	public List<FtpFileInfo> getlistFilesInfo(){
		return this.mFilesInfo;
	}
	/**
	 * 执行刷新远程当前目录列表命令
	 */
	public void startListPath(){
		FileManageTask task=new FileManageTask(browserActivity);
		task.execute(new String[]{REFRESH_PATH});
	}
	/**
	 * 执行远程目录切换命令
	 * @param path 切换文件路径
	 */
	private void changeWorkingDir(String path){
		FileManageTask task=new FileManageTask(browserActivity);
		task.execute(new String[]{CHANGE_FILE_PATH,path});
	}
	/**
	 * 执行文件上传命令
	 * @param context
	 * @param pathData	所以上传文件路径信息
	 */
	public void uploadFile(ArrayList<String> pathData) {
		FileManageTask task=new FileManageTask(browserActivity);
		task.setFilePath(pathData);
		task.execute(new String[]{UPLOAD_FILE});
	}
	/**
	 * 执行文件下载命令
	 * @param context
	 * @param pathData	下载到本地文件位置路径
	 */
	public void downLoadFile(String pathData) {
		FileManageTask task=new FileManageTask(browserActivity);
		task.execute(new String[]{DOWNLOAD_FILE,pathData});
	}
	/**
	 * 执行删除远程文件命令
	 */
	public void deleteFile(){
		FileManageTask task=new FileManageTask(browserActivity);
		task.execute(new String[]{DELETE_FILE});
	}
	/**
	 * 执行文件复制准备
	 * @return
	 */
	public boolean copy() {
		if(mCheck4Paste.size()>0)
			mCheck4Paste.clear();
		for(FtpFileInfo ftpFileInfo : mFilesInfo){
			if(ftpFileInfo.isChecked()){
				mCheck4Paste.add(ftpFileInfo);
			}
		}
		return false;
	}
	/**
	 * 执行文件粘贴
	 * @param isMoveFile
	 */
	public void paste(boolean isMoveFile) {
	//	ArrayList<String> fileNames = new ArrayList<String>();
		String path = mCheck4Paste.get(0).getFilePath();
		/*for(FileInfo files : mCheck4Paste){
			fileNames.add(files.getFileRAWName());
		}*/
		if(isMoveFile){
			FileManageTask task=new FileManageTask(browserActivity);
			task.setFileInfo((ArrayList<FtpFileInfo>)mCheck4Paste);
			task.execute(new String[]{MOVE_FILE,path,getNowLoadingPath()});
		}else{
			FileManageTask task=new FileManageTask(browserActivity);
			task.setFileInfo((ArrayList<FtpFileInfo>)mCheck4Paste);
			task.execute(new String[]{COPY_FILE,path,getNowLoadingPath()});
		}
	}
	/**
	 * 执行文件移动准备
	 * @return
	 */
	public boolean move() {
		if(mCheck4Paste.size()>0)
			mCheck4Paste.clear();
		for(FtpFileInfo ftpFileInfo : mFilesInfo){
			if(ftpFileInfo.isChecked()){	
				mCheck4Paste.add(ftpFileInfo);
			}
		}
		return true;
	}
	 /**
	  * 建立ftp连接
	  * @param params
	  * @return
	  */
	 public boolean connectClient(String... params){
	    	boolean isSuccess = false;
			try {
				ftpClient.setConnectTimeout(20000);
				ftpClient.connect(params[0]);
			//	ftpClient.connect(params[1],Integer.parseInt(params[2]));
				ftpClient.enterLocalPassiveMode();
				int reply;
				reply = ftpClient.getReplyCode();
				if (FTPReply.isPositiveCompletion(reply)) {
					if (ftpClient.login(params[1], params[2])) {
						ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
						ftpClient.setSoTimeout(20000);
						ftpClient.setDataTimeout(20000);
						ftpClient.setFileTransferMode(FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE);
						ftpClient.setDefaultTimeout(20000);
						Log.d(tag, "ftp server connector succuss");
						
						return true;
					}
				}
				ftpClient.disconnect();
			} catch (SocketException e) {
				Log.e(tag, "ftp connect error");
				/*Message m=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, "connect ftpServer fail");
    			m.sendToTarget();*/
			} catch (IOException e) {
				Log.e(tag, "ftp login fail");
			}
	    	return isSuccess;
	    }
	 	/**
		 * 获取当前目录下所以文件
		 * @param files
		 */
		 private void getClientFiles(FTPFile[] files){
				
		    	if(mFilesInfo.size()>0)
		    		mFilesInfo.clear();
			  	SimpleDateFormat  sdFormat = new  SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			  	int length = files.length;
				for(int i = 0; i<length; i++){
					FTPFile file = files[i];
					FtpFileInfo ftpFileInfo = new FtpFileInfo();
					
					String str = file.getName();
					try {
						str = new String(str.getBytes(FTP_DEFAULT_CODE),GBK);
					} catch (UnsupportedEncodingException e) {
						Log.e(tag, e.getMessage());
					}
					ftpFileInfo.setFileName(str);
					ftpFileInfo.setFileRAWName(file.getName());
					try {
						ftpFileInfo.setFilePath(ftpClient.printWorkingDirectory());
					} catch (IOException e) {
						Log.e(tag, e.getMessage());
					}
					
					ftpFileInfo.setDirectory(file.isDirectory());
					
					if(file.isDirectory()){
						ftpFileInfo.setFileSize("");
					}else{
						ftpFileInfo.setFileSize(String.valueOf(file.getSize()));
					}
					
					Date date = file.getTimestamp().getTime();
					ftpFileInfo.setLastModified(String.valueOf(sdFormat.format(date)));
					ftpFileInfo.setFtpFile(file);
					mFilesInfo.add(ftpFileInfo);
					
				}
			}
	 /**
	  * 断开ftp连接
	  */
	 public void disConnectClient() {
			if(null == ftpClient)return;
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				Log.e(tag, "ftp close fail");
			}
		}
	 /**
	  * 返回键事件处理
	  * @param keyCode
	  * @param event
	  * @return
	  */
	 public boolean onKeyUp(int keyCode, KeyEvent event) {
		//	if(keyCode == KeyEvent.KEYCODE_BACK){
				return onKeyBackEvent();
		//	}
		//	return false;
		}
	 /**
	  * 返回按键事件
	  * @return
	  */
	private boolean onKeyBackEvent(){
			int stackSize = mStackNowPath.size();
		
			if(stackSize <= 1){
				//activity.finish and ftp close 
				disConnectClient();
				browserActivity.finish();
			}else{
				mStackNowPath.remove(stackSize - 1);
				
				String path = "";
				for(String str : mStackNowPath){
					path += str;
				}
				changeWorkingDir(path);
			}
			return false;
		}
	/**
	 * item 点击选项监听
	 * @param position
	 */
	public void onItemClickListener(int position) {
		FTPFile ftpFile = mFilesInfo.get(position).getFtpFile();
		if(ftpFile.isDirectory()){
			changeWorkingDir(position);
		}else{
			//to open it
		}
	}
	
	public void onItemLongClick(int arg2) {
		
		
	}
	 /**
	  * 获取当前路径
	  * @return
	  */
	 private String getNowLoadingPath(){
			String allPath = "";
			try {
				allPath += ftpClient.printWorkingDirectory();
			} catch (IOException e) {
				Log.e(tag, e.getMessage());
			} 
			if(!allPath.endsWith(dirChar)){allPath += dirChar;}
			return allPath;
		}
	
		/**
		 * 打开下一个目录
		 * @param item
		 */
		private void changeWorkingDir(int item){
			String itemFileName = mFilesInfo.get(item).getFileRAWName() + dirChar ;
			mStackNowPath.add(itemFileName);
			changeWorkingDir(itemFileName);
		}
		/**
		 * 上传本地文件到ftp服务器
		 * @param uploadFilePath 上传文件路径
		 * @param remoteFilePath 到服务器端文件地址
		 */
		private boolean uploadFiles(FTPClient ftp,String uploadFilePath,String remoteFilePath){
			boolean isSuccess = false;
			InputStream local = null;
			try {
				if (ftp.listFiles(remoteFilePath) == null || ftp.listFiles(remoteFilePath).length == 0) {
					ftp.makeDirectory(remoteFilePath);
					Log.e(tag, "create file : " + remoteFilePath);
				}
				local = new FileInputStream(uploadFilePath);
				String str [] = uploadFilePath.split(dirChar);
				int length = str.length;
				String fileName = str[length - 1];
				isSuccess = ftp.storeFile(fileName, local);
			} catch (FileNotFoundException e) {
				Log.e(tag, "not found uploadFile error");
			}catch (IOException e) {
				Log.e(tag, "file upload inputstream error");
			}finally{
				if(null != local){
					try {
						local.close();
					} catch (IOException e) {
						Log.e(tag, "upload inputstream close error");
					}
				}
			}
			String str = "";
			if(isSuccess){
				str = "upload file success!";
			}else{
				str = "upload file failed!";
			}
			Log.d(tag, str);
			return isSuccess;
		}
		/**
		 * 下载ftp服务器端文件到本地
		 * @param ftp
		 * @param fileName	要下载文件名称
		 * @param filePaths	下载到本地文件位置
		 * @param localPath	要下载文件所在路径
		 * @return
		 */
		private boolean downloadFiles(FTPClient ftp,String fileName,String filePaths,String localPath) {
			boolean success = false;
			OutputStream out=null;
			try {
				int reply;
				reply = ftp.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftp.disconnect();
					return success;
				}
				/*String filePath = localPath + fileName;
				File localFile = new File(localPath);
				if(!localFile.exists()){localFile.mkdirs();}*/
				
				File localFileDir=new File(localPath);
				if(!localFileDir.exists()) {localFileDir.mkdir();}
				String filePath = localPath +dirChar+ fileName;
				File localFile = new File(filePath);
				if(!localFile.exists()){localFile.createNewFile();}
				
				out = new FileOutputStream(localFile);
				ftp.retrieveFile(filePaths, out);
				success = true;
			} catch (IOException e) {
				Log.e(tag, "dnException= "+e.getMessage());
			}finally{
				if(out!=null){
					try {
						out.close();
					} catch (IOException e) {
						Log.e(tag, "dn outstream close dn error");
					}
				}
			}
			
			String str = "";
			if(success){
				str = "dnload file success!";
			}else{
				str = "dnload file failed!";
			}
			Log.d(tag, str);
			return success;
		}
		/**
		 * 删除多个文件
		 * @param ftp
		 * @return
		 */
		private boolean deleteFiles(FTPClient ftp){
			boolean success = false;
			FileAdapter adapter = browserActivity.getFileAdapter();
			List<FtpFileInfo> listChecked = adapter.getCheckedListFiles();
		//	List<FtpFileInfo> listChecked=FileInfo.checkListInfo;
			
			if(null == listChecked || listChecked.size() <= 0){
				return success;
			}
			String nowPath = getNowLoadingPath();
			for(FtpFileInfo ftpFileInfo : listChecked){
					String fileName = nowPath + ftpFileInfo.getFileRAWName();
					try {
						success = ftp.deleteFile(fileName);
					} catch (IOException e) {
						Log.e(tag, "delete file error");
					}
			}
			
			String str = "";
			if(success){
				str = "delete file success!";
			}else{
				str = "delete file failed!";
			}
			Log.d(tag, str);
			return success;
		}
		/**
		 * 删除单个文件
		 * @param pos	文件信息位置
		 */
		public void deleteOneFile(int pos){
			boolean success=false;
			FtpFileInfo ftpFileInfo=mFilesInfo.get(pos);
			String nowPath = getNowLoadingPath();
			String fileName = nowPath + ftpFileInfo.getFileRAWName();
			try {
				success = ftpClient.deleteFile(fileName);
			} catch (IOException e) {
				Log.e(tag, "delete file error");
			}
			
			String str = "";
			if(success){
				str = "delete file success!";
			}else{
				str = "delete file failed!";
			}
			Message msg=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, str);
			msg.sendToTarget();
			browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
		}
		
		private boolean copyFiles(FTPClient ftp,String oldDir,FTPFile ftpFile,String fileName,String remotePath){
			boolean success = false;
		    try {
		    	File localFileDir=new File(TEMP_FILE_DIR);
				if(!localFileDir.exists()) {localFileDir.mkdir();}
				String tempFilePath = TEMP_FILE_DIR +dirChar+ fileName;
				File localFile = new File(tempFilePath);
				if(!localFile.exists()){localFile.createNewFile();}
				
		    	OutputStream out = new FileOutputStream(localFile);
				ftp.retrieveFile(oldDir+ftpFile.getName(), out);//down
				out.close();
				
		//		ftp.changeWorkingDirectory(remotePath);
				InputStream local = new FileInputStream(localFile);
				success = ftp.storeFile(remotePath+fileName,local);//upload	
				local.close();
				
		//		ftp.changeWorkingDirectory(oldDir);
				localFile.delete();
			} catch (IOException e) {
				success = false;
				Log.e(tag, "copy file error");
			}
		    String str = "";
			if(success){
				str = "copy file success!";
			}else{
				str = "copy file failed!";
			}
			Log.d(tag, str);
			return success;
		}
		/**
		 * 多个文件移动
		 * @param ftp
		 * @param oldDir	文件原位置目录
		 * @param fileName	文件名称
		 * @param remotePath	移动到远程文件目录
		 * @return
		 */
		private boolean moveFiles(FTPClient ftp,String oldDir,String fileName,String remotePath){	
			boolean isSuccess = false;
		    try {
		    	isSuccess = ftp.rename(oldDir+fileName, remotePath + fileName); 
			} catch (IOException e) {
				isSuccess = false;
				Log.e(tag, "move file error");
			}
		    String str = "";
			if(isSuccess){
				str = "move file success!";
			}else{
				str = "move file failed!";
			}
			Log.d(tag, str);
			return isSuccess;
		}
		/**
		 * 单个文件移动前文件位置
		 * @return
		 */
		public String oldMovePathBefore(){
			String path=getNowLoadingPath();
			return path;
		}
		/**
		 * 单个文件移动
		 * @param pos	移动文件信息位置
		 * @param oldDir	源文件位置
		 */
		public void moveOneFile(int pos,String oldDir){
			boolean isSuccess = false;
			FTPFile ftpFile=mFilesInfo.get(pos).getFtpFile();
			
		    try {
		    	isSuccess = ftpClient.rename(oldDir+ftpFile.getName(), getNowLoadingPath() + ftpFile.getName()); 
			} catch (IOException e) {
				isSuccess = false;
				Log.e(tag, "move file error");
			}
		    String str = "";
			if(isSuccess){
				str = "move file success!";
			}else{
				str = "move file failed!";
			}
			Message msg=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, str);
			msg.sendToTarget();
			browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
		}
		
		public void showFileRenameDialog(final FtpFileInfo file){
			final Context context=browserActivity;
			
			final View myView = LayoutInflater.from(context).inflate( R.layout.file_rename_dialog,null);
			final EditText edt = (EditText)myView.findViewById(R.id.edtFileRename);
			edt.setText(file.getFileName());
		    AlertDialog renameDialog = new AlertDialog.Builder(context).create();
		    renameDialog.setView(myView);
			renameDialog.setCancelable(true);
		    renameDialog.setButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {

					String newName = String.valueOf(edt.getText());
					if(newName == null || newName.length() <= 0){
						Toast.makeText(context, "name isn't null", Toast.LENGTH_SHORT).show();
						return ;
					}else{
						try {
							String path = file.getFilePath();
							if(!path.endsWith(dirChar)){path += dirChar;}
							final boolean isSuccess=ftpClient.rename(path+file.getFileRAWName(), path+newName);
							String str = "";
							if(isSuccess){
								str = "rename file success!";
							}else{
								str = "rename file failed!";
							}
							Toast.makeText(browserActivity, str, Toast.LENGTH_SHORT).show();
							browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
						} catch (IOException e) {
							Log.e(tag, "rename file error");
						}
					}
				}
			});
		    renameDialog.setButton2(context.getString(android.R.string.cancel),
		    new DialogInterface.OnClickListener(){
		      @Override
			public void onClick(DialogInterface dialog, int which){
		   
		      }
		    });
		    renameDialog.show();
		}
		
	 /**
	  * 文件处理站
	  * @author Andy
	  *
	  */
	 private class FileManageTask extends AsyncTask<String, String, String>{

		
		    private ProgressDialog pgdialog;
			private Context mcontext;
			private List<String> filePaths;
			private List<FtpFileInfo> fs;
			
			public FileManageTask(Context mcontext){
				this.mcontext=mcontext;
				
			}
			
			public void setFilePath(ArrayList<String> fileData){
				this.filePaths = fileData;
			}
			
			public void setFileInfo(ArrayList<FtpFileInfo> fileData){
				this.fs=fileData;
			}
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if(null != pgdialog && pgdialog.isShowing())return;

				pgdialog = new ProgressDialog(mcontext);
			//	pgdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				pgdialog.setMessage("Please wait...");
	            pgdialog.setIndeterminate(true);
	            pgdialog.setCancelable(false);
	            pgdialog.show();
			}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			
		}

		@Override
		protected String doInBackground(String... params) {
			
			String result = params[0];
			if(REFRESH_PATH.equals(params[0])){
				FTPFile[] files;
				try {
					files = ftpClient.listFiles();
					getClientFiles(files);
				} catch (IOException e) {
					Log.e(tag, e.getMessage());
				}
			}
			else if(CHANGE_FILE_PATH.equals(params[0])){
			//	Log.e(tag, "changeWorkingDir : " + params[1]);
				try {
					ftpClient.changeWorkingDirectory(params[1]);
					FTPFile[] files = ftpClient.listFiles();
					getClientFiles(files);
				} catch (IOException e) {
					Log.e(tag, e.getMessage());
				}
			}
			else if(UPLOAD_FILE.equals(params[0])){
				int size = filePaths.size();
				for(int i = 0; i<size; i++){
					uploadFiles(ftpClient,filePaths.get(i),getNowLoadingPath());
				//	Log.e(tag, filePaths.get(i) + "is uploaded.");
				}
			}
			else if(DOWNLOAD_FILE.equals(params[0])){
				
				FileAdapter adapter = browserActivity.getFileAdapter();
				List<FtpFileInfo> listChecked = adapter.getCheckedListFiles();
				
				if(null == listChecked || listChecked.size() <= 0){
					result=null;
					return result;
				}
				for(FtpFileInfo files : listChecked){
						String path = files.getFilePath();
						if(!path.endsWith(dirChar)){path += dirChar;}
						downloadFiles(ftpClient,files.getFileName(),path+ files.getFileRAWName(),params[1]);
				}
				
			}
			else if(DELETE_FILE.equals(params[0])){
				deleteFiles(ftpClient);
			}
			else if(COPY_FILE.equals(params[0])){
				
				for (FtpFileInfo oldInfo : fs) {
					FTPFile oldFtpFile=oldInfo.getFtpFile();
					boolean results = copyFiles(ftpClient,params[1]+dirChar,oldFtpFile,oldFtpFile.getName(),params[2]);
					if(!results){result = null;}
				}
			}
			else if(MOVE_FILE.equals(params[0])){
				
				for (FtpFileInfo oldInfo : fs) {
					FTPFile ftpFile=oldInfo.getFtpFile();
					moveFiles(ftpClient,params[1]+dirChar,ftpFile.getName(),params[2]);
				}
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			if(UPLOAD_FILE.equals(result)){
				doInBackground(REFRESH_PATH);
			}else if(DELETE_FILE.equals(result)){
				doInBackground(REFRESH_PATH);
			}else if(DOWNLOAD_FILE.equals(result)){
				doInBackground(REFRESH_PATH);
			}else if(COPY_FILE.equals(result)){
				doInBackground(REFRESH_PATH);
			}else if(MOVE_FILE.equals(result)){
				doInBackground(REFRESH_PATH);
			}
			browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
			pgdialog.dismiss();
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			pgdialog.dismiss();
		}
	 }
	 
	 
}

account.java

package com.ftpbrowser.sample;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class FtpAccount {


	private String tag = "FtpAccounts";
	private Context mContext;
	//view

	private EditText mEdtFTPDialogAddress;
	private EditText mEdtFTPDialogPort;
	private EditText mEdtFTPDialogUserName;
	private EditText mEdtFTPDialogPWD;
	
	private Button mBtnDialogOK;
	private View inflaterView;
	private FtpUtils ftpUtil;
	
	public FtpAccount(Context context){
		
		initView(context);
	}
	
	private void initView(Context context){
		mContext = context;
		ftpUtil = new FtpUtils();
		mContext = context;
		
		inflaterView = LayoutInflater.from(context).inflate(R.layout.account_layout, null);
		
		mEdtFTPDialogAddress = (EditText)inflaterView.findViewById(R.id.edtFTPaddress);
		mEdtFTPDialogPort = (EditText)inflaterView.findViewById(R.id.edtFtpDialogProt);
		mEdtFTPDialogUserName = (EditText)inflaterView.findViewById(R.id.edtFTPUserName);
		mEdtFTPDialogPWD = (EditText)inflaterView.findViewById(R.id.edtFTPPassword);
	
		mBtnDialogOK = (Button)inflaterView.findViewById(R.id.btnFTPDilaogOK);
		mBtnDialogOK.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(!ftpUtil.netWorkAvaliable(mContext)){
					Toast.makeText(mContext, "net isn't working.", Toast.LENGTH_SHORT).show();
					return ;
				}else{
					new ConnectClientTask().execute(new String[]{mEdtFTPDialogAddress.getText().toString(),mEdtFTPDialogUserName.getText().toString(),
							mEdtFTPDialogPWD.getText().toString()});
				}
			}
		});
		
		initData();
	}
	
	private void initData(){
		
			mEdtFTPDialogAddress.setText("192.168.1.186");
			mEdtFTPDialogPort.setText("21");
			mEdtFTPDialogUserName.setText("ftpCount");
			mEdtFTPDialogPWD.setText("111");
	}
	
	public View getView(){
		return this.inflaterView;
	}
	
	private class ConnectClientTask extends AsyncTask<String, String, String>{
		private ProgressDialog pgdialog;
		private boolean isSuccess = false;
		
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			pgdialog = new ProgressDialog(mContext);
			pgdialog.setMessage("Please wait while loading...");
            pgdialog.setIndeterminate(true);
            pgdialog.setCancelable(false);
            pgdialog.show();
            
		}
		
		@Override
		protected String doInBackground(String... params) {
			/*
			for(String str:params){
				Log.e(tag, str);
			}*/
			isSuccess = FtpFileManage.getInstance().connectClient(params);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(isSuccess){
				Log.d(tag, "ConnectClientTask isSuccess");
				Intent intent = new Intent(mContext,FtpBrowserActivity2.class);
				mContext.startActivity(intent);
			}else{
				Log.e(tag, "ConnectClientTask failed");
				Toast.makeText(mContext, "connect failed.", Toast.LENGTH_SHORT).show();
			}
			pgdialog.dismiss();
		}
	}
	
	public class FtpInfo{
		//model
		private int id;
		private String clientType;
		private String address;
		private int port;
		private String userName;
		private String pwd;
		
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		
		public String getClientType() {
			return clientType;
		}
		public void setClientType(String clientType) {
			this.clientType = clientType;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		public int getPort() {
			return port;
		}
		public void setPort(int port) {
			this.port = port;
		}
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public String getPwd() {
			return pwd;
		}
		public void setPwd(String pwd) {
			this.pwd = pwd;
		}
	}
	
}

FtpBrowserActivity2.java

package com.ftpbrowser.sample;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class FtpBrowserActivity2 extends Activity implements OnItemClickListener{
	
	public static final int REFRESH_DATA=1;
	public static final int STARTLIST_DATA=2;
	public static final int EMPTY_DATA=-1;
	
	public static FtpBrowserActivity2 browserActivity;
	private ListView fileListView;
	private FileAdapter adapter;
	private List<Map<String, Object>> items;
	final static String STORE_DIRECTORY=Environment.getExternalStorageDirectory().getAbsolutePath();
	FtpFileManage ma;
	List<FtpFileInfo> Infofiles;
	boolean firstStart=true;
	
	Handler mHandler=new Handler(){
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
				case STARTLIST_DATA:
					ma.startListPath();
					break;
				case REFRESH_DATA:
					listDir(false);
					break;
				case EMPTY_DATA:
					Toast.makeText(browserActivity, msg.obj.toString(), 200).show();
					break;
			}
		};
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setTitle("远程文件管理");
        View v=LayoutInflater.from(this).inflate(R.layout.main, null);
        setContentView(v);
        registerForContextMenu(v);
        FtpBrowserActivity2.browserActivity=this;
        fileListView = (ListView) findViewById(R.id.ftpFilelist);
        ma=FtpFileManage.getInstance();
        ma.setActivity();
      //  new ConnectFtpServer().start();
    }
    
    class ConnectFtpServer extends Thread{
    	@Override
    	public void run() {
    		
    	//	boolean success=ma.connectClient(new String[]{"192.168.1.186","ftpCount", "111"});
    		boolean success=ma.connectClient(new String[]{"192.168.1.186","ftpServer", "11"});
    		if(success){
    			mHandler.sendEmptyMessageDelayed(STARTLIST_DATA, 1000);
    		}else{
    			Message m=mHandler.obtainMessage(EMPTY_DATA, "please check ftp server normal");
    			m.sendToTarget();
    		}
    	}
    }
    
    private List<Map<String, Object>> bindList(){

		List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
		Infofiles=ma.getlistFilesInfo();
			
			for (FtpFileInfo file : Infofiles){
				Map<String, Object> map = new HashMap<String, Object>();
				if(file.isDirectory()){
					map.put(FileAdapter.FILE_IMAGE, R.drawable.directory);
				}else{
					map.put(FileAdapter.FILE_IMAGE, R.drawable.file_doc);
				}
				map.put(FileAdapter.FILE_NAME, file.getFileName());
				map.put(FileAdapter.FILE_PATH, file.getFilePath());
				map.put(FileAdapter.FTP_FILE_INFO, file);
				list.add(map);
			}
			return list;
	}
    
    private void listDir(boolean choose){
    	items=bindList();
    	adapter = new FileAdapter(getApplicationContext(), items,choose);
		adapter.setFile_type(FileType.FTP_FILE_TYPE);
        fileListView.setAdapter(adapter);
        fileListView.setOnItemClickListener(this);
        fileListView.setOnItemLongClickListener(new ChooseDialog());
        fileListView.setSelection(0);
    }
    
    @Override
    protected void onResume() {
    	if(firstStart){
    		firstStart=false;
    		mHandler.sendEmptyMessageDelayed(STARTLIST_DATA, 1000);
    	}
    	super.onResume();
    }
    
   private boolean isMove=false;
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	

    	return super.onPrepareOptionsMenu(menu);
    }
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, Menu.FIRST, 0, "choose file");
		menu.add(1, Menu.FIRST+1, 0, "upload file");
		menu.add(1, Menu.FIRST+2, 0, "download file");
		menu.add(2, Menu.FIRST+3, 0, "move file");
		menu.add(2, Menu.FIRST+4, 0, "copy file");
		menu.add(3, Menu.FIRST+5, 0, "delete file");
		menu.add(3, Menu.FIRST+6, 0, "paste file");
		
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i=new Intent(this,LoacalFileActivity.class);
		
		
		switch(item.getItemId()){
		case Menu.FIRST:
			listDir(true);
			break;
		case Menu.FIRST+1:
			startActivityForResult(i, 0);
			break;
		case Menu.FIRST+2:
			ma.downLoadFile(STORE_DIRECTORY+File.separator+"temp");
			break;
		case Menu.FIRST+3:
			isMove=ma.move();
			break;
		case Menu.FIRST+4:
			isMove=ma.copy();
			break;
		case Menu.FIRST+5:
			ma.deleteFile();
			break;
		case Menu.FIRST+6:
			ma.paste(isMove);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	int pastePos=0;
	String oldDir="";
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		menu.add(0, Menu.FIRST, 0, "paste");
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
    	switch (item.getItemId()) {  
    	case 1:
    		ma.moveOneFile(pastePos, oldDir);
			break;
    	}
		return super.onContextItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(resultCode){
		
		case 11:
			
			ArrayList<String> filesPath=(ArrayList<String>)FileInfo.upFilePath;
			if(filesPath!=null&&filesPath.size()>0){
				ma.uploadFile(filesPath);
				Toast.makeText(getApplicationContext(), "upload local file......", 200).show();
			}else{
				Toast.makeText(getApplicationContext(), "upload file fail", 200).show();
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
    public FileAdapter getFileAdapter(){
    	return adapter;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	
    	if(keyCode == KeyEvent.KEYCODE_BACK){
    		return ma.onKeyUp(keyCode, event);
    	}
    	else{
    		return super.onKeyUp(keyCode, event);
    	}
    }
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		ma.onItemClickListener(arg2);
		FTPFile ftpFile = Infofiles.get(arg2).getFtpFile();
			if (ftpFile.isDirectory()){
			//	listDir();
			}
			else{
				Toast.makeText(this,"no directry",Toast.LENGTH_SHORT).show();
			}
	} 
	
	class ChooseDialog implements android.widget.AdapterView.OnItemLongClickListener{

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			AlertDialog.Builder builder=new AlertDialog.Builder(browserActivity);
			
			String[] items={"rename file","delete file","move file","copy file"};
			builder.setItems(items, new LongDialog(arg2));
			builder.create().show();
			return true;
		}
	}
	/**
	 * 文件操作选择
	 * @author Administrator
	 *
	 */
	class LongDialog implements DialogInterface.OnClickListener{
		private int pos=0;
		
		public LongDialog(int pos){
			this.pos=pos;
		}
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch(which){
			case 0:
				ChooseDialog(0,pos);
				break;
			case 1:
				ChooseDialog(1,pos);
				break;
			case 2:
				ChooseDialog(2,pos);
				break;
			case 3:
				break;
			}
		}
	}
	/**
	 * 文件操作提示
	 * @param id
	 */
	private void ChooseDialog(final int id,final int pos){
		
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		
		switch(id){
		case 0:
			 ma.showFileRenameDialog(Infofiles.get(pos));
			break;
		case 1:
			builder.setTitle("你确定要删除该文件吗?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ma.deleteOneFile(pos);
				}
			});
            builder.setNegativeButton("取消",null);
			break;
		case 2:
			builder.setTitle("你确定要移动该文件吗?");
			 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						oldDir=ma.oldMovePathBefore();
					}
				});
	            builder.setNegativeButton("取消",null);
			break;
		case 3:
			builder.setTitle("你确定复制该文件吗?");
			 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
					}
				});
	            builder.setNegativeButton("取消",null);
			break;
		}
		builder.create().show();
	}
	
}

以上代码足够学习研究了,服务器是自己找的,已经上传

http://download.csdn.net/detail/yudajun/5140876

如有不懂还请留言交流。



2014/4/25更新,详细代码已上传

点击打开链接










原文地址:https://www.cnblogs.com/happyxiaoyu02/p/6818961.html