首页 > 代码库 > Java操作SFTP
Java操作SFTP
import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;/** * @description SFTP工具 * @author Luxh */public class SFTPUtils { private static final Logger Log = LoggerFactory.getLogger(SFTPUtils.class); /**FTP协议*/ private static final String FTP_PROTOCOL = "sftp"; /** * 获取session * @param host * @param port * @param username * @param password * @return */ public static Session getSession(String host, int port, String username, String password) { Session session = null; try { Log.info("init session..."); JSch jsch = new JSch(); session = jsch.getSession(username, host, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Log.info("init session successful"); }catch(Exception e) { Log.error("init session failed"); } return session; } /** * 获取 ChannelSftp * @param session * @return */ public static ChannelSftp getChannelSftp(Session session){ ChannelSftp sftp = null; try{ Log.info("init ChannelSftp..."); Channel channel = session.openChannel(FTP_PROTOCOL); channel.connect(); sftp = (ChannelSftp) channel; Log.info("init ChannelSftp successful"); }catch(Exception e) { Log.error("init ChannelSftp failed"); } return sftp; } /** * 上传 * @param src 源文件路径 * @param dst 目标文件路径 * @param sftp */ public static void upload(String src, String dst, ChannelSftp sftp) { try { Log.info("begin upload..."); Log.info("src file is:{}", src); Log.info("dst file is:{}", dst); sftp.put(src, dst); Log.info("upload successful"); } catch (Exception e) { Log.error("upload failed"); } } /** * 下载 * @param src 要下载的文件 * @param dst 存放路径 * @param sftp */ public static void download(String src, String dst, ChannelSftp sftp) { try { Log.info("begin download..."); Log.info("src file is:{} ", src); Log.info("dst file is:{} ", dst); sftp.get(src, dst); Log.info("download successful"); } catch (Exception e) { Log.error("download failed"); } } /** * 删除 * @param path 要删除的文件路径 * @param sftp */ public static void delete(String path, ChannelSftp sftp) { try { Log.info("begin delete..."); Log.info("dst file is: {}", path); sftp.rm(path); Log.info("delete successful"); } catch (Exception e) { Log.error("delete failed"); } } /** * 关闭连接 * @param session * @param sftp */ public static void close(Session session, ChannelSftp sftp){ if(sftp != null) { sftp.disconnect(); Log.info("ChannelSftp disconnect"); } if(session != null) { session.disconnect(); Log.info("Session disconnect"); } } }
Java操作SFTP
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。