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);
}
}
}
}
}
从FTP下载文件到本地
最新推荐文章于 2023-08-11 15:08:56 发布