SFTP 文件操作

   Secure File Transfer Protocol的缩写,安全文件传送协议。

1、连接

ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			//获取会话对象
			Session sshSession = jsch.getSession(username, host, port);
			System.out.println("Session created.");
			//向会话对象植入密码
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			//连接会话
			sshSession.connect();
			System.out.println("Session connected.");
			System.out.println("Opening Channel.");
			//获得会话通道
			Channel channel = sshSession.openChannel("sftp");
			//连接
			channel.connect();
			sftp = (ChannelSftp) channel;
			 System.out.println("Connected to " + host + ".");
		  } catch (Exception e) {
		
		  }
		  return sftp;

 

 2、操作

 //上传文件
		try {
			sftp.cd(directory);
			File file=new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());
			System.out.println("上传成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//下载文件
		try {
			sftp.cd(directory);
			File file=new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
		} catch (Exception e) {
			e.printStackTrace();
		}
		//删除文件
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
		 } catch (Exception e) {
			e.printStackTrace();
		 }

 3、断开连接(还有session会话、channel对象)//根据项目情况断开连接

if(null != channel ){
			 System.out.println("断开Channel连接");
			 channel.disconnect();
		 }
		 
		 if(null != sftp ){
			 System.out.println("断开ChannelSftp连接");
			 sftp.disconnect();
		 }
		 
		 if(null != sshSession ){
			 System.out.println("断开Session连接");
			 sshSession.disconnect();
		 }

 4、测试


		public static final String HOST = "x.x.x.x";
		public static final int PORT =**;
		public static final String USERNAME = "**";
		public static final String PASSWORD = "***";
		public static final String DIRECTORY = "/ent/post_res/";
		
		public static void main(String[] args) {
			
			SFTPUploadBean sf = new SFTPUploadBean(); 
			//本地文件
			String uploadFile = "G:\\sftp.txt";
			//连接
			ChannelSftp sftp=sf.connect(HOST, PORT, USERNAME, PASSWORD);
			//操作
			sf.upload(DIRECTORY, uploadFile, sftp);
			//关闭连接
			sf.free(sftp);
			System.exit(0);
			
		}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值