1 引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.15</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2 工具类
package ftp;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.IOException;
public class FtpUtil {
public static String download(String remoteFile, String localFile, String ip, Integer port, String username, String password, FtpMode ftpMode) {
if(StringUtils.isBlank(localFile)) {
return "本地保存路径及名称不能为空";
}
File lFile = FileUtil.file(localFile);
Ftp ftp = null;
try {
ftp = new Ftp(ip,port == null ? 21 : port,username,password);
if(ftpMode != null) {
ftp.setMode(ftpMode);
}
ftp.download(remoteFile, lFile);
} catch (Exception e) {
return e.getMessage();
} finally {
try {
if(ftp != null) ftp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(lFile.exists() && lFile.length() > 0) {
return "success";
} else {
lFile.delete();
return "download failure,"+ remoteFile +" maybe not exists !!";
}
}
public static String upload(String remoteDir, String localFile, String ip, Integer port, String username, String password, FtpMode ftpMode) {
return upload(remoteDir, null, localFile, ip, port, username, password, ftpMode);
}
public static String upload(String remoteDir, String remoteFileName, String localFile, String ip, Integer port, String username, String password, FtpMode ftpMode) {
if(StringUtils.isBlank(localFile)) {
return "本地文件名称不能为空";
}
File lFile = FileUtil.file(localFile);
if(!lFile.exists()) {
return "本地文件不存在";
}
Ftp ftp = null;
try {
ftp = new Ftp(ip,port == null ? 21 : port,username,password);
if(ftpMode != null) {
ftp.setMode(ftpMode);
}
if(StringUtils.isBlank(remoteFileName)) {
ftp.upload(remoteDir, lFile);
} else {
ftp.upload(remoteDir, remoteFileName, lFile);
}
} catch (Exception e) {
return e.getMessage();
} finally {
try {
if(ftp != null) ftp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "success";
}
}
3 测试
public class FtpTest {
public static void main(String[] args) {
String result = FtpUtil.upload("opt/upload","fff.zip", "D:/STM.zip", "192.168.68.55", 21, "ftpuser", "ftpuser!@#123", null);
System.out.println(result);
String result2 = FtpUtil.download("opt/upload/fff.zip", "D:/bbb.zip", "192.168.68.55", 21, "ftpuser", "ftpuser!@#123", null);
System.out.println(result2);
}
}