今天给大家分享一下使用Ftp 下载文件夹
首先说一下 流程, 我们需要用java代码先将我们需要下载的文件夹压缩成一个zip文件 然后我们在用户下载文件的方法 去下载这个zip 就可以
第一步 我们需要导入两个包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
第二步 我们需要创建两个工具类 JSCHUtil
/**
* @author Xiaoliu
* @date 2019/5/8
* @description xhell 命令工具类
*/
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.InputStream;
import java.util.Properties;
public class JSCHUtil {
private static JSCHUtil instance;
private JSCHUtil() {
}
public static JSCHUtil getInstance() {
if (instance == null) {
instance = new JSCHUtil();
}
return instance;
}
private Session getSession(String host, int port, String userName) throws JSchException {
JSch jSch = new JSch();
Session session = jSch.getSession(userName, host, port);
return session;
}
public Session connect(String host, int port, String ueseName,
String password) throws Exception {
Session session = getSession(host, port, ueseName);
session.setPassword(password);
Properties config = new Properties();
config.setProperty("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
return session;
}
public String execCmd(Session session, String command)
throws Exception {
if (session == null) {
throw new RuntimeException("Session is null!");
}
ChannelExec exec = (ChannelExec) session.openChannel("exec");
InputStream in = exec.getInputStream();
byte[] b = new byte[1024];
exec.setCommand(command);
exec.connect();
StringBuffer buffer = new StringBuffer();
while (in.read(b) > 0) {
buffer.append(new String(b));
}
exec.disconnect();
return buffer.toString();
}
public static void clear(Session session) {
if ((session != null) && session.isConnected()) {
session.disconnect();
session = null;
}
}
}
测试一下能用不
public static void main(String[] args) throws Exception {
Session session = JSCHUtil.getInstance()
.connect("192.168.108.246", 22, "root", "hadoop");
String cmd = "ls /home";
String result = JSCHUtil.getInstance().execCmd(session, cmd);
// ???????;??
System.out.println(result);
System.exit(0);
}
现在说明我们已经可以用我们的Java 去执行我们linux 命令了
下面我们就需要去 压缩你想要的文件了 然后去下载
创建工具方法
/**
* ftp 下载文件夹
*
* @param url 服务ip
* @param port 端口号
* @param username 用户名
* @param password 密码
* @param remotePath 服务器相对路径
* @param fileName 文件名称
* @return byte
* @throws Exception
*/
public static byte[] downDirectory(String url, int port, String username, String password, String remotePath, String fileName) throws Exception {
// 用于接口文件流
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
// 创建盒子
FTPClient ftp = new FTPClient();
try {
int reply;
// 打开盒子大门
ftp.connect(url, port);
// 登录
ftp.login(username, password);
// 获取连接返回值
reply = ftp.getReplyCode();
// 返回 500 ,530 都是失败
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return byteStream.toByteArray();
}
// 设置字符集
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
// 发送 Linux xhell 命令
Session session = JSCHUtil.getInstance().connect("192.168.108.246", 22, "root", "hadoop");
// 命令
String cmd = "zip -r /home/ftp_shypt/shypt/yl_merchant_images/images.zip /home/ftp_shypt/shypt/yl_merchant_images";
// 因为我的用户的权限不够 下载文件夹 所以我需要在变更一下文件权限
String result = JSCHUtil.getInstance().execCmd(session, cmd);
String cmd1 = "chown -R ftp_shypt:ftp_shypt /home/ftp_shypt/shypt/yl_merchant_images/images.zip";
String result1 = JSCHUtil.getInstance().execCmd(session, cmd1);
JSCHUtil.clear(session);
System.out.println(result);
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
// 获取path下的所有文件
String[] fs = ftp.listNames();
for (String ff : fs) {
String ftpName = ff;
if (ftpName.equals(fileName)) {
try (InputStream is = ftp.retrieveFileStream(new String(ftpName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1))) {
byte[] buffer = new byte[BUFFER_SIZE];
int len = -1;
while ((len = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
byteStream.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
ftp.disconnect();
}
}
return byteStream.toByteArray();
}
写个测试方法 测试一下
public static void main(String[] args) throws Exception {
byte[] data = downDirectory("192.168.108.246", 21, "ftp_shypt", "ftp_shypt", "shypt/yl_merchant_images", "images.zip");
File file = new File("E:\\images.zip");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
}
注意我是直接将他下载到我本机了 你可以获取byte[] 流 用 HttpServletResponse response 将流 写出成一个文件zip 就完成浏览器下载
public void downDirectory(HttpServletResponse response) throws IOException, JSchException {
System.out.println("初始化成功");
try {
byte[] data = downDirectory(URL, PORT, USERNAME, PASSWD, PATH,"images.zip");
response.addHeader("Content-Disposition", "attachment;filename= " + "images.zip");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
ServletOutputStream out = response.getOutputStream();
out.write(data);
} catch (Exception e) {
e.printStackTrace();
}
}