java连接远程服务器远程写入文件Demo

一、导入maven依赖:

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

2.Demo示例:

package com.igenetech.manage.utils;

import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;


public class UploadFileUtil {

   //jsonArray是要写入的内容,使用时可忽略,换成自己的参数。。
    public static void upLoadToIgenetech(String content, String fileName){
        String dPath="/usr/demo/";
        JSch jsch = new JSch();
        Session session = null;
        try {
            //用户名、ip地址、端口号
            session = jsch.getSession("username", "192.168.1.100", 22);
        } catch (JSchException e) {
            e.printStackTrace();
        }
        // 设置登陆主机的密码
        session.setPassword("password");// 设置密码
        // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        // 设置登陆超时时间
        try {
            session.connect(300000);
        } catch (JSchException e) {
            e.printStackTrace();
        }
        Channel channel = null;
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            String lastPath = DateTimeUtils.format(new Date(), "yyyyMM");
            try {
                sftp.cd(dPath+lastPath);
                } catch (SftpException e) {

                sftp.mkdir(dPath+lastPath);
                sftp.cd(dPath+lastPath);

            }
            OutputStream o = null;
            File file = new File(dPath+lastPath + "/" + fileName);
            o = sftp.put(file.getName());File(dPath+lastPath+"/"+fileName));
            o.write(content.toString().getBytes("UTF-8"));
            o.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            channel.disconnect();
        }
    }

   
}

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值