当前位置: 移动技术网 > IT编程>开发语言>Java > java实现sftp客户端上传文件以及文件夹的功能代码

java实现sftp客户端上传文件以及文件夹的功能代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

虐杀原形2寻找塞维尔,qq乐园,临邑酷牛网

1.依赖的jar文件 jsch-0.1.53.jar

2.登录方式有密码登录,和密匙登录

 代码:

主函数:

import java.util.properties;

import com.cloudpower.util.login;
import com.util.loadproperties;

public class ftp {
  public static void main(string[] args) {
    properties properties = loadproperties.getproperties();
    login.login(properties);
  }
}

登陆页面的代码:

package com.cloudpower.util;

import java.io.console;
import java.util.properties;

import com.jcraft.jsch.jsch;
import com.jcraft.jsch.session;

public class login {

  public static void login(properties properties) {
    string ip = properties.getproperty("ip");
    string user = properties.getproperty("user");
    string pwd = properties.getproperty("pwd");
    string port = properties.getproperty("port");
    string privatekeypath = properties.getproperty("privatekeypath");
    string passphrase = properties.getproperty("passphrase");
    string sourcepath = properties.getproperty("sourcepath");
    string destinationpath = properties.getproperty("destinationpath");

    if (ip != null && !ip.equals("") && user != null && !user.equals("")
        && port != null && !port.equals("") && sourcepath != null
        && !sourcepath.equals("") && destinationpath != null
        && !destinationpath.equals("")) {

      if (privatekeypath != null && !privatekeypath.equals("")) {
        sshsftp2(ip, user, integer.parseint(port), privatekeypath,
            passphrase, sourcepath, destinationpath);
      } else if (pwd != null && !pwd.equals("")) {
        sshsftp(ip, user, pwd, integer.parseint(port), sourcepath,
            destinationpath);
      } else {
        console console = system.console();
        system.out.print("enter password:");
        char[] readpassword = console.readpassword();
        sshsftp(ip, user, new string(readpassword),
            integer.parseint(port), sourcepath, destinationpath);
      }
    } else {
      system.out.println("请先设置配置文件");
    }
  }

  /**
   * 密码方式登录
   * 
   * @param ip
   * @param user
   * @param psw
   * @param port
   * @param spath
   * @param dpath
   */
  public static void sshsftp(string ip, string user, string psw, int port,
      string spath, string dpath) {
    system.out.println("password login");
    session session = null;

    jsch jsch = new jsch();
    try {
      if (port <= 0) {
        // 连接服务器,采用默认端口
        session = jsch.getsession(user, ip);
      } else {
        // 采用指定的端口连接服务器
        session = jsch.getsession(user, ip, port);
      }

      // 如果服务器连接不上,则抛出异常
      if (session == null) {
        throw new exception("session is null");
      }

      // 设置登陆主机的密码
      session.setpassword(psw);// 设置密码
      // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
      session.setconfig("stricthostkeychecking", "no");
      // 设置登陆超时时间
      session.connect(300000);
      uploadfile.uploadfile(session, spath, dpath);
    } catch (exception e) {
      e.printstacktrace();
    }

    system.out.println("success");
  }

  /**
   * 密匙方式登录
   * 
   * @param ip
   * @param user
   * @param port
   * @param privatekey
   * @param passphrase
   * @param spath
   * @param dpath
   */
  public static void sshsftp2(string ip, string user, int port,
      string privatekey, string passphrase, string spath, string dpath) {
    system.out.println("privatekey login");
    session session = null;
    jsch jsch = new jsch();
    try {
      // 设置密钥和密码
      // 支持密钥的方式登陆,只需在jsch.getsession之前设置一下密钥的相关信息就可以了
      if (privatekey != null && !"".equals(privatekey)) {
        if (passphrase != null && "".equals(passphrase)) {
          // 设置带口令的密钥
          jsch.addidentity(privatekey, passphrase);
        } else {
          // 设置不带口令的密钥
          jsch.addidentity(privatekey);
        }
      }
      if (port <= 0) {
        // 连接服务器,采用默认端口
        session = jsch.getsession(user, ip);
      } else {
        // 采用指定的端口连接服务器
        session = jsch.getsession(user, ip, port);
      }
      // 如果服务器连接不上,则抛出异常
      if (session == null) {
        throw new exception("session is null");
      }
      // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
      session.setconfig("stricthostkeychecking", "no");
      // 设置登陆超时时间
      session.connect(300000);
      uploadfile.uploadfile(session, spath, dpath);
      system.out.println("success");
    } catch (exception e) {
      e.printstacktrace();
    }
  }

}

文件上传的代码:

package com.cloudpower.util;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.util.scanner;

import com.jcraft.jsch.channel;
import com.jcraft.jsch.channelsftp;
import com.jcraft.jsch.session;
import com.jcraft.jsch.sftpexception;

public class uploadfile {
  public static void uploadfile(session session, string spath, string dpath) {

    channel channel = null;
    try {
      channel = (channel) session.openchannel("sftp");
      channel.connect(10000000);
      channelsftp sftp = (channelsftp) channel;
      try {
        sftp.cd(dpath);
        scanner scanner = new scanner(system.in);
        system.out.println(dpath + ":此目录已存在,文件可能会被覆盖!是否继续y/n?");
        string next = scanner.next();
        if (!next.tolowercase().equals("y")) {
          return;
        }

      } catch (sftpexception e) {

        sftp.mkdir(dpath);
        sftp.cd(dpath);

      }
      file file = new file(spath);
      copyfile(sftp, file, sftp.pwd());
    } catch (exception e) {
      e.printstacktrace();
    } finally {
      session.disconnect();
      channel.disconnect();
    }
  }

  public static void copyfile(channelsftp sftp, file file, string pwd) {

    if (file.isdirectory()) {
      file[] list = file.listfiles();
      try {
        try {
          string filename = file.getname();
          sftp.cd(pwd);
          system.out.println("正在创建目录:" + sftp.pwd() + "/" + filename);
          sftp.mkdir(filename);
          system.out.println("目录创建成功:" + sftp.pwd() + "/" + filename);
        } catch (exception e) {
          // todo: handle exception
        }
        pwd = pwd + "/" + file.getname();
        try {

          sftp.cd(file.getname());
        } catch (sftpexception e) {
          // todo: handle exception
          e.printstacktrace();
        }
      } catch (exception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
      for (int i = 0; i < list.length; i++) {
        copyfile(sftp, list[i], pwd);
      }
    } else {

      try {
        sftp.cd(pwd);

      } catch (sftpexception e1) {
        // todo auto-generated catch block
        e1.printstacktrace();
      }
      system.out.println("正在复制文件:" + file.getabsolutepath());
      inputstream instream = null;
      outputstream outstream = null;
      try {
        outstream = sftp.put(file.getname());
        instream = new fileinputstream(file);

        byte b[] = new byte[1024];
        int n;
        try {
          while ((n = instream.read(b)) != -1) {
            outstream.write(b, 0, n);
          }
        } catch (ioexception e) {
          // todo auto-generated catch block
          e.printstacktrace();
        }

      } catch (sftpexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      } catch (ioexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      } finally {
        try {
          outstream.flush();
          outstream.close();
          instream.close();

        } catch (exception e2) {
          // todo: handle exception
          e2.printstacktrace();
        }
      }
    }
  }

}

读取配置文件的代码:

package com.util;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.properties;

public class loadproperties {
  public static properties getproperties() {

    file file = new file(class.class.getclass().getresource("/").getpath()
        + "properties.properties");

    inputstream inputstream = null;

    try {
      inputstream = new fileinputstream(file);
    } catch (ioexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }

    properties properties = new properties();
    try {
      properties.load(inputstream);
    } catch (ioexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }

    return properties;

  }
}

代码目录结构:

测试运行时配置文件放在项目的bin目录下(打包成可运行jar文件的时候要删除,打包完成后将配置文件和jar包放在同级目录下即可):

properties.properties

ip=
user=
pwd=
port=22
privatekeypath=
passphrase=
sourcepath=
destinationpath=/home/dbbs/f

打包可运行jar文件:

export->java->runnabe jar file

完成后

在控制台运行java -jar  导出jar包的名字.jar 即可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网