欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 之sftp实现

程序员文章站 2022-07-10 16:19:48
...
上周进行了linux环境下sftp的配置和用户权限的创建:http://jiandequn.iteye.com/blog/2414753

今天进行java下对sftp的操作,这里就不多说了,直接上代码
首先依赖包
   <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

SFtpUpload.java 类
package com.jiahejiankang.operation.core.util.sftp;
import com.jcraft.jsch.*;
import org.apache.log4j.Logger;
import java.io.*;
public class SFtpUpload {
    private static Logger log = Logger.getLogger(SFtpUpload.class.getName());
    private ChannelSftp sftp = null;
    private Session sshSession = null;
    public SFtpUpload(Session sshSession) {
        this.sshSession =sshSession;
    }
    /**
     * 通过SFTP连接服务器
     */
    public void connect() {
        try {
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            if (log.isInfoEnabled()) {
                log.info("Opening Channel.");
            }
            sftp = (ChannelSftp) channel;
            if (log.isInfoEnabled()) {
                log.info("Connected to channel..");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                if (log.isInfoEnabled()) {
                    log.info("sftp is closed already");
                }
            }
        }
    }

    /**
     * 删除stfp文件
     *
     * @param directory:要删除文件所在目录
     * @param deleteFile:要删除的文件
     */
    public void deleteSFTP(String directory, String deleteFile) {
        try {
            // sftp.cd(directory);
            sftp.rm(directory + deleteFile);
            if (log.isInfoEnabled()) {
                log.info("delete file success from sftp.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     *
     * @param createpath
     * @return
     */
    public boolean createDir(String createpath) {
        try {
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
                return true;
            }
            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);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

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

    /**
     * 上传单个文件
     *
     * @param remotePath:远程保存目录
     * @param remoteFileName:保存文件名
     * @param localPath:本地上传目录(以路径符号结束)
     * @param localFileName:上传的文件名
     * @return
     */
    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 e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * @param remotePath 远程路径名
     * @param file       文件格式
     * @return
     */
    public boolean uploadFile(String remotePath, File file) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            in = new FileInputStream(file);
            sftp.put(in, file.getName());
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     *
     * @param remotePath 目录
     * @param inputStream   流
     * @param remoteFileName 远程文件名
     * @return
     */
    public boolean uploadFile(String remotePath, InputStream inputStream, String remoteFileName) {
        try {
            createDir(remotePath);
            sftp.put(inputStream, remoteFileName);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}


SftpFactory.java类
package com.jiahejiankang.operation.core.util.sftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jiahejiankang.operation.core.util.ProperManager;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public class SftpFactory {
    private static Logger log = Logger.getLogger(SftpFactory.class.getName());
    private static final String HOST = "192.168.1.44";
    private static final String USERNAME = "mysftp";
    private static final String PWD = "123";
    private static final Integer PORT = "22";
    private static final String SFTP_PATH = "upload";
    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    private static Session sshSession = null;
    public static SFtpUpload getSFtpUpload() {
        sshSession = getSession(USERNAME,HOST,PORT,PWD);
        SFtpUpload sFtpUpload = new SFtpUpload(sshSession);
        atomicInteger.getAndIncrement();
        return sFtpUpload;
    }
    private static synchronized Session getSession(String username,String host,Integer port,String pwd) {
        if(sshSession != null){
            return sshSession;
        }
        JSch jsch = new JSch();
        try {
            sshSession = jsch.getSession(username, host, port);
            if (log.isInfoEnabled()) {
                log.info("Session created.");
            }
            sshSession.setPassword(pwd);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            if (log.isInfoEnabled()) {
                log.info("Session connected.");
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return sshSession;
    }
    public static String upload(String dir, File file) {
        SFtpUpload sFtpUpload = getSFtpUpload();
            try {
                sFtpUpload.connect();

                if(!sFtpUpload.uploadFile(SFTP_PATH+"/"+dir,file)){
                    throw new Exception("上传失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                sFtpUpload.disconnect();
                atomicInteger.getAndDecrement();
                disconnect();
            }
        StringBuffer sb = new StringBuffer("sftp://");
        sb.append(USERNAME).append(":").append(PWD)
                .append("@").append(HOST).append(":").append(PORT)
                .append("/").append(SFTP_PATH).append("/").append(dir).append("/").append(file.getName());
         return sb.toString();
    }
    public static void disconnect(){
        if(atomicInteger.intValue() == 1){
            sshSession.disconnect();
        }
    }
}
相关标签: java、sftp