从FTP下载文件到本地


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

/**
* 〈一句话功能简述〉<br>
* 〈功能详细描述〉
*
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class TestFtpClient {

Logger logger = LoggerFactory.getLogger(TestFtpClient.class);

/**
*
* 从FTP下载文件到本地 <br>
* 〈功能详细描述〉
*
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@Test
public void testDownloadFileToLocal() throws Exception {
// 从FTP上下载文件并打成ZIP包给用户下载
FTPClient ftpClient = null;
FileOutputStream fos = null;

try {
// 创建ftp连接对象
ftpClient = new FTPClient();
ftpClient.connect("192.168.1.1", 21);
// 登陆ftp服务器
ftpClient.login("test", "test");
// 设置文件的传输类型,默认是ASCII,修改为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据
ftpClient.enterLocalPassiveMode();
// 切换到指定目录中,如果切换失败说明目录不存在
boolean boo = ftpClient.changeWorkingDirectory("luxiaofeng/b");
// 如果切换路径失败,说明拼接的路径有问题,抛出异常
if (!boo) {
return;
}

fos = new FileOutputStream(new File("D:\\a.sql"));
// If the current file type is ASCII, line separators in the file are converted to the local representation.
// 如果当前的文件类型(ftpClient.setFileType)是ASCII,行分隔符将转化为本地的格式
ftpClient.retrieveFile(new String("相关脚本.sql".getBytes("GBK"), "ISO-8859-1"), fos);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
// 关闭ftp连接
if (null != ftpClient) {
try {
ftpClient.disconnect();
} catch (IOException e) {
logger.error("关闭FTP连接异常", e);
}
}
// 关闭zip文件输出流
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
logger.error("IO异常", e);
}
}
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值