android 基於apache ftp server

來源:互聯網
上載者:User

最近研究了一下在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 伺服器功能

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.