这里先做个简单的文件下载例子,先入门再说。
package com.vakinge.ftp;
import java.io.File;
import java.io.FileNotFoundException;
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.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class ClientFtpApp {
private String ip = "localhost";
private int port = 21;
private String username = "admin";
private String password = "admin";
/**
* @param args
*/
public static void main(String[] args) {
ClientFtpApp ftp = new ClientFtpApp();
ftp.downLoadFile("c:\\w\\", "./good/", "阿发.txt");
}
public void downLoadFile(String localPath, String remotePath, String fileName) {
FTPFile[] files = null;
FTPClient client = null;
try {
int reply;
if (client == null) {
try {
client = new FTPClient();
client.setControlEncoding("utf-8");
client.setDefaultPort(port);
client.connect(ip, port);
client.login(username, password);
reply = client.getReplyCode();
client.setDataTimeout(120000);
System.out.println(ip + " 连接成功");
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
System.out.println(ip + " connect refused!");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println(ip + " 连接超时!");
} catch (IOException e) {
e.printStackTrace();
System.out.println(ip + " 服务器无法打开!");
}
}
client.changeWorkingDirectory(remotePath);
files = client.listFiles();
for (FTPFile f : files) {
if (f.getName().equals(fileName)) {
File localFile = new File(localPath + File.separator
+ fileName);
FileOutputStream fos = new FileOutputStream(localFile);
client.retrieveFile(fileName, fos);
fos.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (client != null) {
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
前提:阅读上一篇文章配置ftp server。
在浏览器中输入:ftp://127.0.0.1
右键“登录”,输入用户名和密码 admin/admin
新建good/阿发.txt(可直接从window中拖动过来)
运行上面的程序下载good文件夹内容
可在c:/w目录中看到阿发.txt
参考:
http://vakinge.iteye.com/blog/487486
http://hi.baidu.com/victorlin23/blog/item/edc62a35dbae8a1a91ef3947.html