利用Apache提供的ftp下载工具类下载ftpServer数据

private static FTPClient ftpClient = new FTPClient();


// 连接ftp服务器

private boolean connectServer(String ip, String user, String password) {
//FTP服务器的IP地址;user:登录FTP服务器的用户名;password:登录FTP服务器的用户名的口令;path:FTP服务器上的
// 路径
try {
ftpClient.connect(ip);
ftpClient.login(user, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//指定文件类型,解决下载后文件大小变化的问题
} catch (Exception e1) {
e1.printStackTrace();
}
return true;

}


private void downloadSingleFile(String ip, String username, String pwd, String filePath, String fileName, String fileType)
throws IOException {
// 连接ftp
connectServer(ip, username, pwd);

//解决中文路径的问题
filePath = new String(filePath.getBytes("GBK"), "iso-8859-1");
fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
ftpClient.changeWorkingDirectory(filePath);
InputStream is = ftpClient.retrieveFileStream(fileName);

//下载文件
download(is, fileName, fileType);
}

//利用struts下载

public void download(InputStream brSource, String fileName, String fileType) {
HttpServletResponse res = ServletActionContext.getResponse();
try {
if (brSource == null) {
String url = this.getRequest().getScheme() + "://" + this.getRequest().getServerName() + ":"
+ this.getRequest().getServerPort() + this.getRequest().getContextPath() + "/" + "fileNotFound.jsp";
this.getResponse().sendRedirect(url);
return;
}
// InputStream brSource = new BufferedInputStream(new FileInputStream(file));
int len = 0;
// 清空输出流
res.reset();
// 设定输出文件头
res.setContentType("application/x-" + fileType + "-compressed;charset=utf-8");
res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1"));
// res.addHeader("Content-Length", ""+brSource.available());
OutputStream out = new BufferedOutputStream(res.getOutputStream());
int i = 0;
byte[] buffer = new byte[800];
while (true) {
if (brSource.available() < 800) {
while (i != -1) {
i = brSource.read();
out.write(i);
}
break;
} else {
brSource.read(buffer);
out.write(buffer);


}
}
brSource.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}


}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8fc03dbdf57d7181faf6863619ded0c6.html