Android和FTP服务器交互,上传下载文件(实例demo)

今天同学说他备份了联系人的数据放在一个文件里,想把它存到服务器上,以便之后可以进行下载恢复..于是帮他写了个上传,下载文件的demo

主要是 跟FTP服务器打交道~因为这个东东有免费的可以身亲哈

 

1. 首先申请一个免费的FTP空间:

http://www.3v.cm/host/

我这边注册了个账号,密码分别为:

chenww

chenww

 

2. 查看FTP空间的地址(端口默认是21)

FTP服务器: chenww.3vfree.us

端口: 21

 

3. Demo部分

 

主Activity: FTPMainActivity

 

<span style="color:#000000">package com.example.ftpdemo;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/**
 * 2013年09月20日21:28:51 测试demo
 * 
 * 1.文件上传到FTP服务器 
 * 2.从FTP服务器上下载文件
 * 
 * 所需jar包:commons-net-3.0.1.jar
 * 将commons-net-3.0.1.jar放于libs中
 * 
 * @author xiaoyaomeng
 * 
 */
public class FTPMainActivity extends Activity implements OnClickListener {

	//傻逼Buttons
	private Button buttonUpLoad = null;
	private Button buttonDownLoad = null;
	
	//FTP工具类
	private FTPUtils ftpUtils = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ftpmain);
		
		//获取控件对象
		buttonUpLoad = (Button) findViewById(R.id.button_upload);
		buttonDownLoad = (Button) findViewById(R.id.button_download);

		//设置控件对应相应函数
		buttonUpLoad.setOnClickListener(this);
		buttonDownLoad.setOnClickListener(this);
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		
		//初始化和FTP服务器交互的类
		InitFTPServerSetting();
	}

	public void InitFTPServerSetting() {
		// TODO Auto-generated method stub
		ftpUtils = FTPUtils.getInstance();
		boolean flag = ftpUtils.initFTPSetting("chenww.3vfree.us", 21, "chenww", "chenww");
			
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ftpmain, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
							case R.id.button_upload: {
								//上传文件
								
							}
								break;
							case R.id.button_download: {
								//下载文件
								
							}
								break;
							default:
								break;
					
			}
	}
}</span>

 

 

 

 

 

工具类:FTPUtils

 

 

<strong>package com.example.ftpdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

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.R.bool;

/**
 * 2013年09月20日21:38:04
 * 
 * 用于Android和FTP服务器进行交互的工具类
 * 
 * @author xiaoyaomeng
 *
 */
public class FTPUtils {
	private FTPClient ftpClient = null;
	private static FTPUtils ftpUtilsInstance = null;
	private String FTPUrl;
	private int FTPPort;
	private String UserName;
	private String UserPassword;
	
	private FTPUtils()
	{
		ftpClient = new FTPClient();
	}
	/*
	 * 得到类对象实例(因为只能有一个这样的类对象,所以用单例模式)
	 */
	public  static FTPUtils getInstance() {
		if (ftpUtilsInstance == null)
		{
			ftpUtilsInstance = new FTPUtils();
		}
		return ftpUtilsInstance;
	}
	
	/**
	 * 设置FTP服务器
	 * @param FTPUrl   FTP服务器ip地址
	 * @param FTPPort   FTP服务器端口号
	 * @param UserName    登陆FTP服务器的账号
	 * @param UserPassword    登陆FTP服务器的密码
	 * @return
	 */
	public boolean initFTPSetting(String FTPUrl, int FTPPort, String UserName, String UserPassword)
	{	
		this.FTPUrl = FTPUrl;
		this.FTPPort = FTPPort;
		this.UserName = UserName;
		this.UserPassword = UserPassword;
		
		int reply;
		
		try {
			//1.要连接的FTP服务器Url,Port
			ftpClient.connect(FTPUrl, FTPPort);
			
			//2.登陆FTP服务器
			ftpClient.login(UserName, UserPassword);
			
			//3.看返回的值是不是230,如果是,表示登陆成功
			reply = ftpClient.getReplyCode();
		
			if (!FTPReply.isPositiveCompletion(reply))
			{
				//断开
				ftpClient.disconnect();
				return false;
			}
			
			return true;
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 上传文件
	 * @param FilePath    要上传文件所在SDCard的路径
	 * @param FileName    要上传的文件的文件名(如:Sim唯一标识码)
	 * @return    true为成功,false为失败
	 */
	public boolean uploadFile(String FilePath, String FileName) {
		
		if (!ftpClient.isConnected())
		{
			if (!initFTPSetting(FTPUrl,  FTPPort,  UserName,  UserPassword))
			{
				return false;
			}
		}
		
		try {
			
			//设置存储路径
			ftpClient.makeDirectory("/data");
			ftpClient.changeWorkingDirectory("/data");
			
			//设置上传文件需要的一些基本信息
			ftpClient.setBufferSize(1024);  
	        ftpClient.setControlEncoding("UTF-8"); 
	        ftpClient.enterLocalPassiveMode();   
	        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
	        
	        //文件上传吧~
	        FileInputStream fileInputStream = new FileInputStream(FilePath);
	        ftpClient.storeFile(FileName, fileInputStream);
	        
	        //关闭文件流
	        fileInputStream.close();
	        
	        //退出登陆FTP,关闭ftpCLient的连接
	        ftpClient.logout();
	        ftpClient.disconnect();
	        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 下载文件
	 * @param FilePath  要存放的文件的路径
	 * @param FileName   远程FTP服务器上的那个文件的名字
	 * @return   true为成功,false为失败
	 */
	public boolean downLoadFile(String FilePath, String FileName) {
		
		if (!ftpClient.isConnected())
		{
			if (!initFTPSetting(FTPUrl,  FTPPort,  UserName,  UserPassword))
			{
				return false;
			}
		}
		 
		try {
			// 转到指定下载目录
			ftpClient.changeWorkingDirectory("/data");
			
			// 列出该目录下所有文件
			FTPFile[] files = ftpClient.listFiles();
			
			// 遍历所有文件,找到指定的文件
			for (FTPFile file : files) {
				if (file.getName().equals(FileName)) {
					//根据绝对路径初始化文件
					File localFile = new File(FilePath);
					
					// 输出流
					OutputStream outputStream = new FileOutputStream(localFile);
					
					// 下载文件
					ftpClient.retrieveFile(file.getName(), outputStream);
					
					//关闭流
					outputStream.close();
				}
			}
			
			//退出登陆FTP,关闭ftpCLient的连接
	        ftpClient.logout();
	        ftpClient.disconnect();
	        
	        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
	}
	
}</strong>

 

 

 

需要的Jar包下载地址:

commons-net-3.0.1.jar

 

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 46
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 46
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值