import java.io.*;
import java.net.SocketException;
import org.apache.commons.net.ftp.*;
/**
* ftp服务器下载文件
*
*/
public class FtpDownloadFileUtil {
private static String host = "";
private static String user = "";
private static String password = "";
private static String directory = "/home/ftpuser/gsi-war";
private static String saveFile = "D:/saveftp";
/**
* 获取FTPCLIENT
*/
public static FTPClient getFtpClient() throws SocketException, IOException {
FTPClient ftp = new FTPClient();
// 连接FTP服务器
ftp.connect(host);
// 登陆FTP服务器
ftp.login(user, password);
// 验证FTP服务器是否登录成功
int replyCode = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("登录验证失败");
}
// 中文支持
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// ftp.enterLocalPassiveMode(); // 被动模式
ftp.enterLocalActiveMode(); // 主动模式
ftp.changeWorkingDirectory(directory);
return ftp;
}
/**
* FTP下载文件
*/
public static String download() {
OutputStream os = null;
String result = "";
FTPClient ftpClient = new FTPClient();
try {
ftpClient = getFtpClient();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("FTP连接发生异常!", e);
}
try {
// 切换FTP目录
ftpClient.changeWorkingDirectory(directory);
FTPFile[] ftpFiles = ftpClient.listFiles();
// 遍历目录下所有文件
for (FTPFile file : ftpFiles) {
String fileName = file.getName();
if (fileName.indexOf(".") == -1) {
continue;
}
String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
if (".jio".equals(fileTyle)) {
File localFile = new File(saveFile + File.separator + fileName);
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(fileName, os);
// 删除jio文件
ftpClient.deleteFile(fileName);
os.close();
}
}
System.out.println("ftp dowmload over");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
try {
os.close();
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
return result;
}
}
ftpサーバーのダウンロードファイル
おすすめ
転載: blog.csdn.net/iloki/article/details/114107159
おすすめ
ランキング