java在ftp服务器下载文件

/**
 * 
 */
package com.uu.ftp;


import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


/**
 * @author Administrator 下午11:33:02
 */
public class FtpFileLoad {
private String userName = "cwx161583";
private String passWord = "ekil*19344978";
private String ip = "localhost";
private int port = 21;
private FTPClient ftpClient = null;


/**
* 连接ftp服务器,创建连接 FtpFileLoad 2013-9-6 下午11:50:08
*/
public void getConnect() {
if (ftpClient == null) {
int reply;
try {
ftpClient = new FTPClient();
ftpClient.connect(ip);
ftpClient.login(userName, passWord);
ftpClient.setDefaultPort(port);
// ftp服务器的登录返回信息
System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
// 断开连接
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
}
} catch (Exception e) {
System.err.println("登录ftp服务器【" + ip + "】失败");
e.printStackTrace();
}
}
}


/**

* FtpFileLoad 2013-9-7 下午1:30:24
*/
public void getFileList() {
ftpClient.setControlEncoding("utf-8");
try {
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
System.out.println(file.getName());
}


} catch (IOException e) {
e.printStackTrace();
}
}


/**

* FtpFileLoad 2013-9-7 下午1:30:12

* @param remoteFileName
* @param localFileName
*/
public void loadFile(String remoteFileName, String localFileName) {
// 下载文件
BufferedOutputStream buffOut = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(localFileName);
buffOut = new BufferedOutputStream(fos);
ftpClient.retrieveFile(remoteFileName, buffOut);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (buffOut != null)
buffOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


public static void main(String[] args) {


}


}

你可能感兴趣的:(ftp)