1下载jar包
http://mina.apache.org/ftpserver-project/download_1.1.1.html
将jar包文件拷贝到libs目录下如下图所示
在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"; }
最后是访问效果