天天看点

java ftp下载多文件_java实现FTP文件下载

public class FtpApche {

private static FTPClient ftpClient = new FTPClient();

private static String encoding = System.getProperty("file.encoding");

public static boolean downFile(String url, int port, String username,

String password, String remotePath, String fileName,

String localPath) {

boolean result = false;

try {

int reply;

ftpClient.setControlEncoding(encoding);

FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);

conf.setServerLanguageCode("zh");

ftpClient.connect(url, port);

// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftpClient.login(username, password);// 登录

// 设置文件传输类型为二进制

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

// 获取ftp登录应答代码

reply = ftpClient.getReplyCode();

// 验证是否登陆成功

if (!FTPReply.isPositiveCompletion(reply)) {

ftpClient.disconnect();

System.err.println("FTP server refused connection.");

return result;

}

// 转移到FTP服务器目录至指定的目录下

ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));

// 获取文件列表

FTPFile[] fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(fileName)) {

File localFile = new File(localPath + "/" + ff.getName());

OutputStream is = new FileOutputStream(localFile);

ftpClient.retrieveFile(ff.getName(), is);

is.close();

}

}

ftpClient.logout();

result = true;

} catch (IOException e) {

e.printStackTrace();

} finally {

if (ftpClient.isConnected()) {

try {

ftpClient.disconnect();

} catch (IOException ioe) {

}

}

}

return result;

}

public void testDownFile(String resourceFolder,String fileName,String targetFolder) {

try {

String propertiesName="/resources/datasource.properties";

String dataServerIp=PropertiesUtil.getPropertiesValue(propertiesName, "wz.ftp.ip");

String dataServerUsername=PropertiesUtil.getPropertiesValue(propertiesName, "wz.ftp.user");

String dataServerPassword=PropertiesUtil.getPropertiesValue(propertiesName, "wz.ftp.pwd");

boolean flag = downFile(dataServerIp, 21, dataServerUsername,

dataServerPassword, resourceFolder, fileName, targetFolder);

System.out.println(flag);

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

FtpApche fa = new FtpApche();