jsch实现设备间文件读写

依赖包

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.1</version>
</dependency>

工具类类

package com.example.democol.common.util;

import com.example.democol.exception.EmosException;
import com.jcraft.jsch.*;
import com.mchange.v2.log.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.SocketException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

/**
 * @author Chenkl
 * @version $Id: SftpUtils.java,v 1.1 2018/12/13 18:08 Chenkl Exp $
 * Created on 2018/12/13 18:08
 */
public class SftpUtils implements AutoCloseable {

    private static final Logger logger= LoggerFactory.getLogger(SftpUtils.class);

    private Session session = null;
    private ChannelSftp channel = null;


    /**
     * 连接sftp服务器
     *
     * @param serverIP 服务IP
     * @param port     端口
     * @param userName 用户名
     * @param password 密码
     * @throws SocketException SocketException
     * @throws IOException     IOException
     * @throws JSchException   JSchException
     */
    public void connectServer(String serverIP, int port, String userName, String password) throws SocketException, IOException, JSchException {
        JSch jsch = new JSch();
        // 根据用户名,主机ip,端口获取一个Session对象
        session = jsch.getSession(userName, serverIP, port);
        // 设置密码
        session.setPassword(password);
        // 为Session对象设置properties
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // 通过Session建立链接
        session.connect();
        // 打开SFTP通道
        channel = (ChannelSftp) session.openChannel("sftp");
        //        // 建立SFTP通道的连接
        channel.connect();

    }

    /**
     * 自动关闭资源
     */
    public void close() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }

    private List<String> getDirList(String path, String appendPath) throws SftpException {
        if (!appendPath.endsWith("/")) {
            appendPath += "/";
        }
        List<String> result = new ArrayList<>();
        List<String> dirList = this.getDirList(path + appendPath);
        for (String fileName : dirList) {
            result.add(appendPath + fileName);
        }
        return result;
    }

    public long getFileSize(String file) throws SftpException, IOException {
        Vector ls = channel.ls(file);
        if (ls == null) {
            throw new IOException("file " + file + " not found!");
        }
        ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) ls.get(0);
        return temp.getAttrs().getSize();
    }

    


    public List<String> getDirList(String path) throws SftpException {
        List<String> result = new ArrayList<>();
        if (!path.endsWith("/")) {
            path += "/";
        }
        if (channel != null) {
            logger.info("开始获取目录: " + path);
            Vector vv = channel.ls(path);
            if (vv == null || vv.size() == 0) {
                return result;
            } else {
                Object[] aa = vv.toArray();
                for (int i = 0; i < aa.length; i++) {
                    ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i];
                    System.out.println(temp.getFilename());
                    if (temp.getFilename().startsWith(".")) {
                        continue;
                    }
                    if (temp.getAttrs().isDir()) {
                        List<String> dirList = this.getDirList(path, temp.getFilename());
                        result.addAll(dirList);
                    } else {
                        result.add(temp.getFilename());

                    }
                }
            }
            logger.info("获取目录结束: " + path);
        }
        return result;
    }

    public List<String> getFileList(String path) throws SftpException {
        List<String> result = new ArrayList<>();
        if (!path.endsWith("/")) {
            path += "/";
        }
        if (channel != null) {
            logger.info("开始获取目录: " + path);
            Vector vv = channel.ls(path);
            if (vv == null || vv.size() == 0) {
                return result;
            } else {
                Object[] aa = vv.toArray();
                for (int i = 0; i < aa.length; i++) {
                    ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i];
                    System.out.println(temp.getFilename());
                    if (temp.getFilename().startsWith(".")) {
                        continue;
                    }
                    if (temp.getAttrs().isDir()) {
                        List<String> dirList = this.getFileList(path+temp.getFilename());
                        result.addAll(dirList);
                    } else {
                        result.add(temp.getFilename());

                    }
                }
            }
            logger.info("获取目录结束: " + path);
        }
        return result;
    }

    /**
     * 下载文件
     *
     * @param remotePathFile 远程文件
     * @param localPathFile  本地文件[绝对路径]
     * @throws SftpException SftpException
     * @throws IOException   IOException
     */
    public void downloadFile(String remotePathFile, String localPathFile) throws SftpException, IOException {
        try (FileOutputStream os = new FileOutputStream(new File(localPathFile))) {
            if (channel == null)
                throw new IOException("sftp server not login");
            channel.get(remotePathFile, os);
        }
    }

    /**
     * 下载文件
     *
     * @param remotePathFile 远程文件
     * @throws SftpException SftpException
     * @throws IOException   IOException
     */
    public String downloadFile(String remotePathFile) throws SftpException, IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        if (channel == null)
            throw new IOException("sftp server not login");
        channel.get(remotePathFile, outputStream);
        return new String(outputStream.toByteArray());
    }

    /**
     * 下载文件
     * @param remotePathFile 远程文件
     * @param outputStream 输出流
     * @throws SftpException
     * @throws IOException
     */
    public void downloadFile(String remotePathFile, OutputStream outputStream) throws SftpException, IOException {
        if (channel == null)
            throw new IOException("sftp server not login");
        channel.get(remotePathFile, outputStream);
    }

    /**
     * 上传文件
     *
     * @param remoteFile 远程文件
     * @param localFile 本地文件[绝对路径]
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(String remoteFile, File localFile) throws SftpException, IOException {
        try (FileInputStream in = new FileInputStream(localFile)) {
            if (channel == null)
                throw new IOException("sftp server not login");
            channel.put(in, remoteFile);
        }
    }

    /**
     * 上传文件
     *
     * @param remoteFile 远程文件
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(String remoteFile, String content) throws SftpException, IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());
        if (channel == null)
            throw new IOException("sftp server not login");
        channel.put(inputStream, remoteFile);
    }

    /**
     * 上传文件
     * @param remoteFile  远程文件
     * @param inputStream  输入流
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(String remoteFile, InputStream inputStream) throws SftpException, IOException {
        if (channel == null)
            throw new IOException("sftp server not login");
        channel.put(inputStream, remoteFile);
    }

    public void mkdir(String path) throws SftpException {
        logger.info("Create Directory " + path);
        String[] split = path.split("/");
        StringBuilder stringBuilder = new StringBuilder();
        for (String name : split) {
            if (!"".equals(name)) {
                stringBuilder.append("/").append(name);
                if (!this.exists(stringBuilder.toString())) {
                    logger.info("Create Directory " + stringBuilder.toString());
                    channel.mkdir(stringBuilder.toString());
                }
            }
        }
    }

    public boolean exists(String path) {
        try {
            channel.ls(path);
            return true;
        } catch (SftpException e) {
            return false;
        }
    }

    public String getHost() {
        return session.getHost();
    }

    public String getUsername() {
        return session.getUserName();
    }

    /**
     *  获取某个文件大小
     */
    public static long getFileSize(String ip, String name, String psWd, String file){
        SftpUtils sftpUtils = new SftpUtils();
        try {
            sftpUtils.connectServer(ip,22,name,psWd);
            Vector ls = sftpUtils.channel.ls(file);
            ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) ls.get(0);
            return lsEntry.getAttrs().getSize();
        } catch (Exception e){
//            LogUtils.logError(logger, null, e, "获取主机文件大小异常--");
//            throw new ErrorCodeException(ResultCodeEnum.SYS_GET_FILE_SIZE_ERROR);
            throw new EmosException("获取主机文件大小异常");
        } finally {
            sftpUtils.close();
        }

    }

    public static void main(String[] args) throws Exception {
        SftpUtils sftpUtils = new SftpUtils();
        sftpUtils.connectServer("10.10.152.203", 22, "11", "111111");
        List<String> dirList = sftpUtils.getDirList("/home/file_repository");
        System.out.println(dirList);
        sftpUtils.close();
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值