Android使用ApacheFtpServer实现Ftp服务器
为了方便在Android手机和PC电脑之间文件传输和管理,于是想在Android上建立FTP服务器来实现文件访问及管理操作。从网上搜索到,Apache的FtpServer有java版本,便做了一个移植,发现很方便。
1、导入Apache FtpServer依赖jar包
commons-net-ftp-2.0.jar
ftpserver-core-1.0.6.jar
log4j-1.2.14.jar
mina-core-2.0.4.jar
slf4j-api-1.5.2.jar
slf4j-log4j12-1.5.2.jar
2、Android启动FtpServer示例代码
package com.orgcent.ftp;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import android.app.Activity;
import android.os.Bundle;
public class FtpServerActivity extends Activity {
static { //由于Android系统版本原因,有些对ipv6支持存在bug,相关异常看文章底部介绍
System.setProperty("java.net.preferIPv6Addresses", "false");
}
private FtpServer mFtpServer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// try {
// InputStream is = getResources().getAssets().open("log4j.properties");
// Properties prop = new Properties();
// prop.load(is);
//
// File file = new File(getDir("log", MODE_WORLD_WRITEABLE), "ftp.log");
// prop.setProperty("log4j.appender.R.File", file.getAbsolutePath());
// PropertyConfigurator.configure(prop);
// } catch (IOException e) {
// e.printStackTrace();
// }
startFtpServer();
}
private void startFtpServer() {
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
// set the port of the listener
int port = 2221;
factory.setPort(port);
// replace the default listener
serverFactory.addListener("default", factory.createListener());
// start the server
FtpServer server = serverFactory.createServer();
this.mFtpServer = server;
try {
server.start();
} catch (FtpException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(null != mFtpServer) {
mFtpServer.stop();
mFtpServer = null;
}
}
}
通过上面配置基本上就实现Android上FtpServer的建立。关于IPV6支持的bug可以查看解决android网络异常java.net.SocketException: Bad address family
Demo下载地址:http://code.google.com/p/android-custom-view/downloads/list
摘自 萝卜白菜的博客
补充:移动开发 , Android ,