1. FTP服务器下载
首先去Apache官网下载ftp服务器: https://mina.apache.org/ftpserver-project/downloads.html
2、解压到本地
3、修改、查看本地的文件(用户名、密码、端口等)
4、启动:
sh ftpd.sh res/conf/ftpd-typical.xml
5、查看 :
ftp://localhost/
192.168.3.54
6、说明:
7、参考:
https://blog.51cto.com/u_15294985/3009141
https://www.bilibili.com/read/cv23024403/
https://blog.51cto.com/u_16175451/8661830
8、代码:
implementation 'commons-net:commons-net:3.6'
package com.tcp.ftp2;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FTPClientTest {
public static void main(String[] args) {
String server = "192.168.3.54";
int port = 21;
String user = "admin";
String password = "admin";
String remoteDir = "/";
String localFile = "_updateFile.gz";
// String server = "192.168.10.1";
// int port = 6677;
// String user = "root";
// //密码传产品类型,却分不同的产品刷程
// String password = "11";
// String remoteDir = "/";
// String localFile = "_updateFile.gz";
uploadFile(server, port, user, password, remoteDir, localFile);
}
void aa() {
int a = 100;
int b = 1000;
float c = a / b;
float aa = a;
float bb = b;
float cc = aa / bb;
System.out.println(c);
System.out.println(cc);
}
public static boolean uploadFile(String server, int port, String user, String password, String remoteDir, String localFile) {
boolean success = false;
long t1=System.currentTimeMillis();
FTPClient ftp = new FTPClient();
try {
System.out.println("上传开始");
ftp.connect(server, port);
ftp.login(user, password);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// Change working directory if needed
if (remoteDir != null && !remoteDir.isEmpty()) {
ftp.changeWorkingDirectory(remoteDir);
}
// Upload a file to the server
FileInputStream input = new FileInputStream(localFile);
long totalLength = new File(localFile).length();
//进度监听
ftp.setCopyStreamListener(new CopyStreamListener() {
@Override
public void bytesTransferred(CopyStreamEvent event) {
System.out.println(event);
}
@Override
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
float a = totalBytesTransferred;
float b = totalLength;
float progress = a / b;
System.out.println(progress);
}
});
success = ftp.storeFile(new java.io.File(localFile).getName(), input);
input.close();
ftp.logout();
System.out.println("上传完成");
} catch (IOException ex) {
ex.printStackTrace();
success = false;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
long t2=System.currentTimeMillis();
System.out.println(t2-t1);
return success;
}
}