android 搭建FTP服务器

1下载jar包 

http://mina.apache.org/ftpserver-project/download_1.1.1.html

android 搭建FTP服务器

将jar包文件拷贝到libs目录下如下图所示

 android 搭建FTP服务器

 在build.gradle中添加依赖

 

implementation files('libs\\ftpserver-core-1.1.1.jar')
implementation files('libs\\slf4j-log4j12-1.7.21.jar')
implementation files('libs\\log4j-1.2.17.jar')

 

在activity中使用方法

private FtpServer mFtpServer;
String localIp =getIpAddressString();
startFtpServer(localIp,8877);

private void startFtpServer(String hostip,int port){
    Log.d(TAG, "startFtpServer: hostip "+hostip+"port "+port);
    FtpServerFactory serverFactory = new FtpServerFactory();
    ListenerFactory factory = new ListenerFactory();
    serverFactory.addListener("default",factory.createListener());
    factory.setPort(port);
    factory.setServerAddress(hostip);
    serverFactory.addListener("default",factory.createListener());
    BaseUser user = new BaseUser();
    user.setName("admin");
    user.setPassword("123456789");
    user.setEnabled(true);
    user.setMaxIdleTime(3000);
    user.setHomeDirectory("/mnt/sdcard/ftp");
    List<Authority> authorities = new ArrayList<>();
    authorities.add(new WritePermission());
    user.setAuthorities(authorities);
    try{
        serverFactory.getUserManager().save(user);
    }
    catch (FtpException e){
        e.printStackTrace();
    }
    if(mFtpServer!=null){
        mFtpServer.stop();
    }
    mFtpServer = serverFactory.createServer();
    try{
        mFtpServer.start();
    }catch (Exception e){
        e.printStackTrace();
    }
    Log.d(TAG, "startFtpServer: startok");
}

public static String getIpAddressString() {
    try {
        for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
            NetworkInterface netI = enNetI.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = netI
                    .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "0.0.0.0";
}

最后是访问效果 

android 搭建FTP服务器

上一篇:使用axios向thinkphp后台post数据时的问题


下一篇:一文彻底弄懂工厂模式(Factory)