使用 apache 的 FtpClient 可以很容以的实现ftp 上传,下载文件
demo如下:
package ftp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
* java 实现 ftp 文件上传,下载
* @author WWP
* @date 2016-11-28 下午8:40:26
*/
public class FtpTest {
private static final String ftpHost = "132.122.237.15";
private static final int ftpPort = 21;
private static final String username = "wwp";
private static final String password = "123";
private static FTPClient client = null;
private static FileInputStream fis = null;
private static FileOutputStream fos = null;
public static void main(String[] args) {
initFtp();
//uploadFile(localFileName, "/");
downloadFile("/css.chm", "f:/");
}
/**
* ftp 下载文件
* @param ftpFileName ftp文件路径
* @param localFileName 本地下载路径
*/
public static void downloadFile(String ftpFileName, String localFileName) {
if(ftpFileName.contains("/")){
localFileName += ftpFileName.substring(ftpFileName.lastIndexOf("/"));
}
try {
client.setControlEncoding("UTF-8"); // 中文支持
client.setFileType(FTPClient.BINARY_FILE_TYPE); //二进制传输
client.enterLocalPassiveMode();
fos = new FileOutputStream(localFileName);
boolean status = client.retrieveFile(ftpFileName, fos);
System.err.println("下载文件状态: " + status);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 文件上传
*
* @param localFileName
* 本地文件路径
* @param remoteFileName
* ftp 服务器路径
*/
public static void uploadFile(String localFileName, String remoteFileName) {
if (localFileName.contains("/")) {
remoteFileName += localFileName.substring(localFileName.lastIndexOf("/"));
}
try {
client.enterLocalPassiveMode(); // 设置PassiveMode传输
client.setFileType(FTPClient.BINARY_FILE_TYPE); // 以二进制方式传输
fis = new FileInputStream(localFileName);
boolean status = client.storeFile(remoteFileName, fis);
System.out.println("上传文件状态: " + status);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 初始化ftp
*/
public static void initFtp() {
client = new FTPClient();
try {
client.connect(ftpHost, ftpPort);
client.login(username, password);
if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
System.err.println("ftp 连接成功");
} else {
client.disconnect();
System.err.println("ftp 连接失败");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}