Java implements sftp file and folder upload windows and linux

Written in front:

Linux generally comes with sftp, while windows needs to build an sftp server first, such as freesshd, http://www.freesshd.com/?ctt=download , after setting up the sftp service, use the java program to connect to upload and download operations. Special attention should be paid to the upload path when using java to upload to windows sftp. Freesshd will have an sftp home path when building sftp. Upload to D:\sftpupload\test, then the upload path in the code can be set to "/test", must include /

dependent package

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

Tools

package xxx.utils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

public class SftpUtil {

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

    /**
     *
     * @param filePath 文件全路径
     * @param ftpPath 上传到目的端目录
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void uploadFile(String filePath, String ftpPath, String username, String password, String host, Integer port) {
        FileInputStream input = null;
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
//            sshConfig.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            //文件乱码处理
            /*Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("GBK");*/
            File file = new File(filePath);
            copyFile(sftp,file,ftpPath);
            logger.info("================SFTP上传成功!==================");
        } catch (Exception e) {
            logger.error("================SFTP上传失败!==================");
            e.printStackTrace();
        }
    }

    public static void copyFile(ChannelSftp sftp, File file, String pwd) {

        if (file.isDirectory()) {
            File[] list = file.listFiles();
            String fileName = file.getName();
            try {
                try {
                    try {
                        sftp.cd(pwd);
                    } catch (SftpException e) {
                        sftp.mkdir(pwd);
                        logger.info("上传根目录创建成功:" + pwd);
                        sftp.cd(pwd);
                    }
                    Vector ls = sftp.ls(fileName);
                } catch (Exception e) {
                    sftp.mkdir(fileName);
                    System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
                }
                pwd = pwd + "/" + fileName;
                try {

                    sftp.cd(fileName);
                } catch (SftpException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (int i = 0; i < list.length; i++) {
                copyFile(sftp, list[i], pwd);
            }
        } else {
            try {
                sftp.cd(pwd);
            } catch (SftpException e1) {
                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) {
                    e.printStackTrace();
                }

            } catch (SftpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outstream.flush();
                    outstream.close();
                    instream.close();

                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    /**
     * @param directory    SFTP服务器的文件路径
     * @param downloadFile SFTP服务器上的文件名
     * @param saveFile     保存到本地路径
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void downloadFile(String directory, String downloadFile, String saveFile, String username, String password, String host, Integer port) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            if (directory != null && !"".equals(directory)) {
                sftp.cd(directory);
            }
            FileOutputStream output = new FileOutputStream(new File(saveFile));
            sftp.get(downloadFile, output);
            output.close();
            sftp.disconnect();
            sshSession.disconnect();
            System.out.println("================下载成功!==================");
        } catch (SftpException | FileNotFoundException | JSchException e) {
            logger.error("SFTP文件下载异常!", e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String source = "D:\\test\\1";
        String windowsDest = "/";
        String linuxDest = "/home/sftp";
        uploadFile(source ,windowsDest,"administrator" , "123123","192.168.1.69" ,5555 );
        uploadFile(source ,linuxDest,"root" , "123123","192.168.1.67" ,22 );
    }



}

Guess you like

Origin blog.csdn.net/zzchances/article/details/129067202