Android SFTP通信

系统结构

在这里插入图片描述

Step1 引入jar包

在这里插入图片描述
commons-net

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>1.4.1</version>
    </dependency>

com.jcraft.jsch

    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.54</version>
    </dependency>

slf4j-api-1.7.2.jar

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.2</version>
    </dependency>

slf4j-log4j12-1.7.2.jar

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.2</version>
    </dependency>
Step2 SFTPUtil.java
import android.annotation.SuppressLint;
import android.util.Log;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

public class SftpUtil {

    private String host;
    private String username;
    private String password;
    private int port = Utils.SERVER_PORT;
    private ChannelSftp sftp = null;
    private Session sshSession = null;

    /**
     * init sftp.
     */
    public SftpUtil(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    /**
     * connect server via sftp.
     */
    public ChannelSftp connect() {
        JSch jsch = new JSch();
        try {
            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");
            if (channel != null) {
                channel.connect();
            } else {
                LogUtils.logd("SFTP :: channel connecting failed");
            }
            sftp = (ChannelSftp) channel;
        } catch (JSchException exception) {
            exception.printStackTrace();
        }
        return sftp;
    }


    /**
     * 断开服务器.
     */
    public void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                LogUtils.logd("SFTP :: SFTP is closed already");
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                LogUtils.logd("SFTP :: sshSession is closed already");
            }
        }
    }

    /**
     * 单个文件上传.
     */
    public boolean uploadFile(String remotePath, String remoteFileName,
                              String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException exception) {
            exception.printStackTrace();
        } catch (SftpException exception) {
            exception.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 批量上传.
     */
    public boolean bacthUploadFile(String remotePath, String localPath,
                                   boolean del) {
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()
                        && files[i].getName().indexOf("bak") == -1) {
                    synchronized (remotePath) {
                        if (this.uploadFile(remotePath, files[i].getName(),
                                localPath, files[i].getName())
                                && del) {
                            deleteFile(localPath + files[i].getName());
                        }
                    }
                }
            }
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            this.disconnect();
        }
        return false;

    }

    /**
     * 删除文件.
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        if (!file.isFile()) {
            return false;
        }
        return file.delete();
    }

    /**
     * 创建文件.
     */
    public void createDir(String createpath) {
        try {
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
                return;
            }
            String[] pathArry = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    sftp.cd(filePath.toString());
                } else {
                    sftp.mkdir(filePath.toString());
                    sftp.cd(filePath.toString());
                }
            }
            this.sftp.cd(createpath);
        } catch (SftpException exception) {
            LogUtils.loge("STFP Error: 文件创建失败");
            exception.printStackTrace();
        }
    }

    /**
     * 判断目录是否存在.
     */
    @SuppressLint("DefaultLocale")
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpAttrs = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpAttrs.isDir();
        } catch (Exception exception) {
            if (exception.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 在服务器中删除.
     */
    public void deleteSftp(String directory, String deleteFile) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 创建目录.
     */
    public void mkdirs(String path) {
        File file = new File(path);
        String fs = file.getParent();
        file = new File(fs);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 列出目录文件.
     */

    @SuppressWarnings("rawtypes")
    public Vector listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }
}
Step3 MainActivity.java
    /**
     * 上传文件测试.
     */
    public void uploadTest() {
    	mSftp = new SftpUtil("IP", "用户名", "密码");
        new Thread() {
            @Override
            public void run() {
                super.run();
                String localPath = 本地路径;
                String remotePath = 服务器路径;
                mSftp.connect();
                if (mSftp.connect() != null) {
                    LogUtils.logd("Connection Successful");
                    mSftp.bacthUploadFile(remotePath, localPath, false); //多文件上传
                    if (mSftp.bacthUploadFile(remotePath, localPath, true)) {
                    	LogUtils.logd("UPLOAD SUCCESSFUL!");
                    } else {
                        LogUtils.logd("UPLOAD FAILED!");
                    }
                    mSftp.disconnect();

                } else {
                	LogUtils.logd("CONNECTION FAILED!");
                }
            }
        }.start();
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值