android 基于apache ftp server

来源:互联网 发布:淘宝网天天特价在哪里 编辑:程序博客网 时间:2024/05/29 08:58

最近研究了一下在android端实现ftp server 功能,在网上搜了几个,没有能用的基本是各种抄袭,还是自己研究吧

首先到 apache官网下载ftp server 相关jar和配置文件,最新的是Apache FtpServer 1.0.6 Release版本


看一下效果图:





由于是apache已经将ftp server相关的实现封装的很好了,所以实现起来就简单多了

导入路径\apache-ftpserver-1.0.6\common\lib下相关jar包

主要的jar包文件



实现代码:


package com.orgcent.ftp;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import org.apache.ftpserver.FtpServer;import org.apache.ftpserver.FtpServerFactory;import org.apache.ftpserver.ftplet.FtpException;import org.apache.ftpserver.listener.ListenerFactory;import org.apache.ftpserver.ssl.SslConfigurationFactory;import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.widget.TextView;public class FtpServerActivity extends Activity {private FtpServer mFtpServer;private String ftpConfigDir= Environment.getExternalStorageDirectory().getAbsolutePath()+"/ftpConfig/";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);TextView tv=(TextView)findViewById(R.id.tvText);String info="请通过浏览器或者我的电脑访问以下地址\n"+"ftp://"+getLocalIpAddress()+":2221\n";tv.setText(info);File f=new File(ftpConfigDir);if(!f.exists())f.mkdir();copyResourceFile(R.raw.users, ftpConfigDir+"users.properties");Config1();} public String getLocalIpAddress() {    String strIP=null;        try {            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {                NetworkInterface intf = en.nextElement();                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {                    InetAddress inetAddress = enumIpAddr.nextElement();                    if (!inetAddress.isLoopbackAddress()) {                    strIP= inetAddress.getHostAddress().toString();                    }                }            }        } catch (SocketException ex) {            Log.e("msg", ex.toString());        }        return strIP;    } private void copyResourceFile(int rid, String targetFile){        InputStream fin = ((Context)this).getResources().openRawResource(rid);        FileOutputStream fos=null;        int length;try {fos = new FileOutputStream(targetFile);byte[] buffer = new byte[1024];         while( (length = fin.read(buffer)) != -1){            fos.write(buffer,0,length);        }} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{if(fin!=null){try {fin.close();} catch (IOException e) {e.printStackTrace();}} if(fos!=null){ try {fos.close();} catch (IOException e) {e.printStackTrace();} }}    }void Config1(){//Now, let's configure the port on which the default listener waits for connections.FtpServerFactory serverFactory = new FtpServerFactory();        ListenerFactory factory = new ListenerFactory();        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();String[] str ={"mkdir", ftpConfigDir};        try {             Process ps = Runtime.getRuntime().exec(str);            try {                ps.waitFor();            } catch (InterruptedException e) {                e.printStackTrace();            }         }catch (IOException e) {            e.printStackTrace();        }        String filename=ftpConfigDir+"users.properties";//"/sdcard/users.properties";File files=new File(filename);userManagerFactory.setFile(files);        serverFactory.setUserManager(userManagerFactory.createUserManager());// set the port of the listenerfactory.setPort(2221);// replace the default listenerserverFactory.addListener("default", factory.createListener());                // start the serverFtpServer server = serverFactory.createServer(); this.mFtpServer = server;       try {server.start();} catch (FtpException e) {e.printStackTrace();}}void Config2(){//Now, let's make it possible for a client to use FTPS (FTP over SSL) for the default listener.FtpServerFactory serverFactory = new FtpServerFactory();        ListenerFactory factory = new ListenerFactory();        // set the port of the listenerfactory.setPort(2221);// define SSL configurationSslConfigurationFactory ssl = new SslConfigurationFactory();ssl.setKeystoreFile(new File(ftpConfigDir+"ftpserver.jks"));ssl.setKeystorePassword("password");// set the SSL configuration for the listenerfactory.setSslConfiguration(ssl.createSslConfiguration());factory.setImplicitSsl(true);// replace the default listenerserverFactory.addListener("default", factory.createListener());        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();userManagerFactory.setFile(new File(ftpConfigDir+"users.properties"));        serverFactory.setUserManager(userManagerFactory.createUserManager());        // start the serverFtpServer server = serverFactory.createServer(); this.mFtpServer = server;  try {server.start();} catch (FtpException e) {e.printStackTrace();}}@Overrideprotected void onDestroy() {super.onDestroy();if(null != mFtpServer) {mFtpServer.stop();mFtpServer = null;}}}


最重要一步,配置文件修改

配置文件所在目录:apache-ftpserver-1.0.6\res\conf

这里我们主要使用users.properties配置文件,修改内容如下

# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements.  See the NOTICE file# distributed with this work for additional information# regarding copyright ownership.  The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License.  You may obtain a copy of the License at##  http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied.  See the License for the# specific language governing permissions and limitations# under the License.# Password is "admin"ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3ftpserver.user.admin.homedirectory=/mnt/sdcardftpserver.user.admin.enableflag=trueftpserver.user.admin.writepermission=trueftpserver.user.admin.maxloginnumber=0ftpserver.user.admin.maxloginperip=0ftpserver.user.admin.idletime=0ftpserver.user.admin.uploadrate=0ftpserver.user.admin.downloadrate=0ftpserver.user.anonymous.userpassword=adminftpserver.user.anonymous.homedirectory=/mnt/sdcardftpserver.user.anonymous.enableflag=trueftpserver.user.anonymous.writepermission=trueftpserver.user.anonymous.maxloginnumber=20ftpserver.user.anonymous.maxloginperip=2ftpserver.user.anonymous.idletime=300ftpserver.user.anonymous.uploadrate=4800ftpserver.user.anonymous.downloadrate=4800


最后别忘了相关权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >    </uses-permission>    <uses-permission android:name="android.permission.INTERNET" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.READ_PHONE_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.WAKE_LOCK" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>

ok,这样简单的就完成了android端ftp server 服务器功能








原创粉丝点击