当前位置: 首页 > java >正文

SFTP工具类实现文件上传下载_

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;/*** SFTP工具类*/
public class SftpFile {static Session sshSession = null;/*** 获取ChannelSftp*/public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {int port = 0;if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {port = Integer.parseInt(sOnlineSftpPort);}ChannelSftp sftp = null;try {JSch jsch = new JSch();jsch.getSession(username, host, port);sshSession = jsch.getSession(username, host, port);sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;} catch (Exception e) {e.printStackTrace();}return sftp;}/*** 上传*/public static void upload(String directory, String uploadFile, ChannelSftp sftp) {FileInputStream io = null;try {sftp.cd(directory);File file = new File(uploadFile);io = new FileInputStream(file);sftp.put(io, file.getName());} catch (Exception e) {e.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}//删除指定目录下的所有文件static boolean deleteDirFiles(String newsFile, ChannelSftp sftp) {try {sftp.cd(newsFile);ListIterator a = sftp.ls(newsFile).listIterator();while (a.hasNext()) {LsEntry oj = (LsEntry) a.next();SftpFile.delete(newsFile, oj.getFilename(), sftp);}} catch (Exception e) {e.getMessage();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}return true;}/*** 上传本地文件到sftp指定的服务器,** @param directory      目标文件夹* @param uploadFile     本地文件夹* @param sftp           sftp地址* @param remoteFileName 重命名的文件名字* @param isRemote       是否需要重命名  是true 就引用remoteFileName 是false就用默认的文件名字*/public static void upload(String directory, String uploadFile, ChannelSftp sftp, String remoteFileName, boolean isRemote) {FileInputStream io = null;try {boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(directory);isExist = true;isExist = sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}if (!isExist) {boolean existDir = SftpFile.isExistDir(directory, sftp);if (!existDir) {String pathArry[] = directory.split("/");StringBuffer Path = new StringBuffer("/");for (String path : pathArry) {if (path.equals("")) {continue;}Path.append(path + "/");if (!SftpFile.isExistDir(Path + "", sftp)) {// 建立目录sftp.mkdir(Path.toString());// 进入并设置为当前目录}sftp.cd(Path.toString());}}}sftp.cd(directory);File file = new File(uploadFile);io = new FileInputStream(file);if (isRemote) {sftp.put(io, remoteFileName);} else {sftp.put(io, file.getName());}} catch (Exception e) {e.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}public static boolean isExistDir(String path, ChannelSftp sftp) {boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(path);isExist = true;return sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}return isExist;}/*** 上传目录下的多个文件*/public static List<String> uploadZip(String directory, String uploadFile, ChannelSftp sftp, List<String> filePath) {try {List<String> list = new ArrayList<>();boolean existDir = SftpFile.isExistDir(directory, sftp);if (!existDir) {sftp.mkdir(directory);}sftp.cd(directory);int i = 1;for (String newPath : filePath) {FileInputStream io = null;try {File file = new File(uploadFile + newPath);io = new FileInputStream(file);sftp.put(io, newPath);io.close();list.add(newPath);i++;} catch (Exception ex) {ex.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}}}return list;} catch (SftpException e) {e.getMessage();return null;} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}/*** 下载指定文件*/public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {try {sftp.cd(directory);File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));} catch (Exception e) {e.printStackTrace();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}System.out.println("DOWNLOAD SUCCESS!");}/*** 查看指定目录下的所有文件*/public static List<String> check(String directory, ChannelSftp sftp) {List<String> fileList = new ArrayList<>();try {sftp.cd(directory);ListIterator a = sftp.ls(directory).listIterator();while (a.hasNext()) {LsEntry oj = (LsEntry) a.next();System.out.println(oj.getFilename());//fileList.add((String) a.next());}} catch (Exception e) {e.printStackTrace();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}return fileList;}/*** 删除指定路径下的指定文件*/public static void delete(String directory, String deleteFile, ChannelSftp sftp) {try {sftp.cd(directory);sftp.rm(deleteFile);System.out.println("文件:"+deleteFile+" 删除成功!");} catch (Exception e) {e.printStackTrace();}finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}public static void main(String[] args) {//服务器地址,端口,用户名,密码ChannelSftp ftp = getConnectIP("10.0.0.131", "22", "root", "123456");//上传单个文件
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\1.txt", ftp);
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\picture.zip", ftp);//上传文件并重命名
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\1.txt", ftp,"2.txt",true);//删除指定文件
//        delete("/mydata","1.txt",ftp);//查看指定目录下的所有文件
//        check("/mydata",ftp);//从服务器下载文件
//        download("/mydata","2.txt","C:\\Users\\Administrator\\Desktop\\2.txt",ftp);//同时上传多个文件
//        uploadZip("/mydata/picture", "C:\\Users\\Administrator\\Desktop\\picture\\", ftp, Arrays.asList("1.png","2.png"));//删除指定目录下的所有文件deleteDirFiles("/mydata/picture",ftp);}
}
http://www.xdnf.cn/news/9516.html

相关文章:

  • 关于ios点击分享自动复制到粘贴板的问题
  • CEH Practical 实战考试真题与答案
  • C++异步通信-future学习
  • maven项目编译时复制xml到classes目录方案
  • 服务器关机
  • 实验设计与分析(第6版,Montgomery)第4章随机化区组,拉丁方, 及有关设计4.5节思考题4.18~4.19 R语言解题
  • 【OSS】 前端如何直接上传到OSS 上返回https链接,如果做到OSS图片资源加密访问
  • [AI voiceFFmpeg windows系统下CUDA与cuDNN详细安装教程]
  • 记录一次session安装应用recyclerview更新数据的bug
  • Transformer架构详解:从Attention到ChatGPT
  • 数据脱敏后的测试方法
  • 宏的高级应用 ——一种 C 语言的元编程技巧(X-Macro)
  • Rust 学习笔记:关于迭代器的练习题
  • 用 Python 和 Rust 构建可微分的分子势能模型:深入解析 MOLPIPx 库
  • Rust: CString、CStr和String、str
  • 电商售后服务系统与其他系统集成:实现售后流程自动化
  • Eclipse 插件开发 5.3 编辑器 监听输入
  • AI Agent工具全景解析:从Coze到RAGflow,探索智能体自动化未来!
  • Java、Python、PHP 三种语言实现 二进制与十六进制的相互转换
  • 板凳-------Mysql cookbook学习 (八)
  • Java开发经验——阿里巴巴编码规范实践解析4
  • HTML5 视频播放器:从基础到进阶的实现指南
  • TypeScript 索引签名:灵活处理动态属性对象
  • STM32通过KEIL pack包轻松移植LVGL,并学会使用GUI guider
  • CRM系统的数据库结构详细设计
  • 【大模型原理与技术-毛玉仁】第四章 参数高效微调
  • 基本面高股息策略
  • RabbitMQ 与其他 MQ 的对比分析:Kafka/RocketMQ 选型指南(二)
  • c++结构化绑定
  • Python应用while循环猜数字