1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| package com.lab.common.utils.sftp;
import com.jcraft.jsch.*;
import java.io.*; import java.util.List; import java.util.Properties;
public class SFTPUtil {
public static void uploadFileToServer(String host, int port, String username, String password, List<String> pathList, String localFile) throws Exception { JSch jsch = new JSch(); Session session = null; ChannelSftp channelSftp = null; try { session = jsch.getSession(username, host, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel;
for (String path: pathList) { sftpSyncFile(localFile, path, channelSftp); } System.out.println("File uploaded successfully");
} catch (Exception e) { throw e;
} finally { if (channelSftp != null) { channelSftp.disconnect(); } if (session != null) { session.disconnect(); } } }
public static boolean isDirExist(String directory, ChannelSftp sftp) { boolean isDirExistFlag = false; try { SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } return isDirExistFlag; }
public static void createMkdir(String directory, ChannelSftp sftp) throws SftpException { String[] path = directory.split("/"); String sd = ""; for (int i = 1; i < path.length; i++) { sd += "/"+path[i]; if(isDirExist(sd, sftp)){ sftp.cd(sd); } else { sftp.mkdir(sd); sftp.cd(sd); } } }
public static void sftpSyncFile(String localFile, String path, ChannelSftp channelSftp) throws SftpException, IOException { File localFileObj = new File(localFile); FileInputStream fileInputStream = new FileInputStream(localFileObj); String cdPath = path.substring(0, path.lastIndexOf('/')); if (isDirExist(cdPath,channelSftp)) { channelSftp.cd(cdPath); } else { createMkdir(cdPath, channelSftp); channelSftp.cd(cdPath); } channelSftp.put(fileInputStream, path.substring(path.lastIndexOf('/') + 1)); fileInputStream.close(); } }
|