一、先安装sftp服务器
安装包链接->提取码:sftp
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;
import com.ytd.ebos.platform.job.service.MyJob;
public class test {
private transient Logger log = LoggerFactory.getLogger(this.getClass());
private ChannelSftp sftp;
private Session session;
/** SFTP 登录用户名*/
private String username;
/** SFTP 登录密码*/
private String password;
/** 私钥 */
private String privateKey;
/** SFTP 服务器地址IP地址*/
private String host;
/** SFTP 端口*/
private int port;
/**
* 构造基于密码认证的sftp对象
*/
public test(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
/**
* 构造基于秘钥认证的sftp对象 秘钥认证还没测试
*/
public test(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public test(){}
/**
* 连接sftp服务器
* @throws SftpException
*/
public ChannelSftp login() {
try {
JSch jsch = new JSch();
if (privateKey != null) { //秘钥还没测试
jsch.addIdentity(privateKey);// 设置私钥
}
session = jsch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(); // 通过Session建立链接
Channel channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftp = (ChannelSftp) channel;
//System.out.println(sftp.getHome());
return sftp;
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
}
/**
* 关闭连接 server
*/
public void logout(){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
public static void main(String[] args) {
test test = new test("admin", "admin", "127.0.0.1", 8721);
ChannelSftp sftp = test.login();//连接sftp
try {
Vector<String> files = sftp.ls("2");//服务器目录
List ret = new ArrayList<>();
for (int i = 0; i < files.size(); i++){//获取目录下所有的文件名
Object obj = files.elementAt(i);
if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
LsEntry entry = (LsEntry) obj;
if (true && !entry.getAttrs().isDir()){
ret.add(entry.getFilename());
}
if (true && entry.getAttrs().isDir()){
if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")){
ret.add(entry.getFilename());
}
}
}
}
Map<String, List<Object>> map = new HashMap<>();//文件名分组在进行压缩
for (Object obj : ret) {
String fileName = obj.toString();
if (map.size()>0) {
String[] yearName = fileName.split("-");
fileName = yearName[0]+"-"+yearName[1];//得到键名
if (map.containsKey(fileName)) {
List<Object> list = map.get(fileName);
list.add(obj);
}else {
List<Object> list = new ArrayList<>();
list.add(obj);
map.put(fileName, list);
}
}else {
List<Object> list = new ArrayList<>();
String[] yearName = fileName.split("-");
fileName = yearName[0]+"-"+yearName[1];//得到键名
list.add(obj);
map.put(fileName, list);
}
}
try {
String mkdir = "H:/zip/";
File file = new File(mkdir);
if (!file.exists()) {//目录不存在创建目录(临时存储目录)
file.mkdir();
}
Set<String> keySet = map.keySet();
for (String key : keySet) {//文件压缩
List<Object> list = map.get(key);
FileOutputStream fileOutputStream = new FileOutputStream(mkdir+key+".zip");
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
for (Object obj : list) {
//System.out.println(obj);
InputStream ips = sftp.get("2/"+obj);
BufferedInputStream bis = new BufferedInputStream(ips);
ZipEntry zipEntry = new ZipEntry(""+obj);
int length;
String fileName = obj.toString();
fileName = fileName.substring(0,fileName.indexOf("."));
//FileOutputStream fileOutputStream = new FileOutputStream("H:/sfftpFile/"+fileName+".zip");
out.putNextEntry(zipEntry);
byte data[] = new byte[8192];
while ((length = bis.read(data, 0, 8192)) != -1) {
out.write(data, 0, length);
}
bis.close();
}
out.close();
sftp.put(mkdir+key+".zip","1");
}
File[] listFiles = file.listFiles();//删除本地临时存储的文件
for (File file2 : listFiles) {
file2.delete();
}
//sftp.rmdir("2");//删除远程目录
for (String key : keySet) {//删除远程目录下的文件
List<Object> list = map.get(key);
for (Object object : list) {
String filePath = object.toString();
sftp.rm("2/"+filePath);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
test.logout();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}