从FTP上下载文件并打成ZIP包给用户下载


//从FTP上下载文件并打成ZIP包给用户下载
FTPClient ftpClient = null;
ZipOutputStream zipOut = null;

try {
// 创建ftp连接对象
ftpClient = new FTPClient();
ftpClient.connect(FtpContants.FTP_IP, FtpContants.FTP_PORT);
// 登陆ftp服务器
ftpClient.login(FtpContants.FTP_USERNAME, FtpContants.FTP_PWD);
// 设置文件的传输类型,默认是ASCII,修改为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// printWorkingDirectory是用户的工作目录
String basePath = ftpClient.printWorkingDirectory() + "/download/data";
// 切换到指定目录中,如果切换失败说明目录不存在
boolean boo = ftpClient.changeWorkingDirectory(basePath);
// 如果切换路径失败,说明拼接的路径有问题,抛出异常
if (!boo) {
LogUtil.printErrorLog("the directory does not exist ,"
+ "or the user don't hava the enterence to this directory " + basePath);
return;
}

// 这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据
ftpClient.enterLocalPassiveMode();
// 遍历路径下的所有文件
FTPFile[] fileList = ftpClient.listFiles();

response.reset();
// 设置导出文件头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(zipFileName.getBytes(LANGUE_GBK), LANGUE_ISO));
// 定义Zip输出流
zipOut = new ZipOutputStream(response.getOutputStream());

byte[] byteReader = new byte[BYTE_INIT_SIZE];
ByteArrayOutputStream os = null;
for (FTPFile tempFile : fileList) {
if (tempFile.isFile()) {
os = new ByteArrayOutputStream();
String downFileName = new String(tempFile.getName().getBytes(LANGUE_GBK), LANGUE_ISO);
// 从FTP上下载downFileName该文件把该文件转化为字节数组的输出流
ftpClient.retrieveFile(downFileName, os);
byte[] bytes = os.toByteArray();
InputStream ins = new ByteArrayInputStream(bytes);

int len;
zipOut.putNextEntry(new ZipEntry(tempFile.getName()));
// 读入需要下载的文件的内容,打包到zip文件
while ((len = ins.read(byteReader)) > 0) {
zipOut.write(byteReader, 0, len);
}
}
}
zipOut.flush();
} catch (IOException e) {
LogUtil.printErrorLog(e.getMessage());
} finally {
// 关闭ftp连接
if (null != ftpClient) {
try {
ftpClient.disconnect();
} catch (IOException e) {
LogUtil.printErrorLog("close Ftp connection error :" + e.getMessage());
}
}
// 关闭zip文件输出流
if (null != zipOut) {
try {
zipOut.closeEntry();
zipOut.close();
} catch (IOException e) {
LogUtil.printErrorLog("close ZipOutputStream connection error :" + e.getMessage());
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值