使用的是 Apache 的 commons-net 实现的。
import java.io.File; import java.io.FileInputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; /** * FTP 连接,上传 * @author lc * @web www.liuchang.org * 2015-10-29 */ public class FTPUtil { public static String SUCCESS = "S"; public static String ERROR = "E"; private FTPClient ftp = null; /** * 建立连接 * @param url * @param port * @param username * @param password */ public void connect(String url, int port, String username, String password){ ftp = new FTPClient(); try { ftp.connect(url, port); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new RuntimeException("FTP connect error, ReplyCode :" + reply); } } catch (Exception e) { disconnect(); e.printStackTrace(); } } /** * 文件上传 * @param directory 上传目录 * @param uploadFile 本地文件目录 * @param saveFileName 文件名 * @return */ public String uploadFile(String directory, String uploadFile, String saveFileName){ if(ftp == null){ System.out.println("create connect before upload file"); return ERROR; } try { ftp.changeWorkingDirectory(directory); ftp.storeFile(saveFileName, new FileInputStream(new File(uploadFile))); } catch (Exception e) { disconnect(); e.printStackTrace(); return ERROR; } return SUCCESS; } public void disconnect(){ if(ftp != null){ try { ftp.logout(); } catch (Exception e) { e.printStackTrace(); } } } }