与下游联调时遇到的问题, 一般我们会使用ftp来传递文件, 因为sftp的传输效率很低. 所以为了兼容,引用了网上的方法. 步骤
1. 导入 Jsch-0.1.54.jar直接去maven库中下载即可2. 编写工具类--SFTPUtil.java1 /** 2 * @author shansm 3 * @date 2020/3/18 -17:27 4 */ 5 public class SFTPUtil { 6 7 private transient Logger log = LoggerFactory.getLogger(this.getClass()); 8 9 private ChannelSftp sftp; 10 11 private Session session; 12 /** SFTP 登录用户名*/ 13 private String username; 14 /** SFTP 登录密码*/ 15 private String password; 16 /** 私钥 */ 17 private String privateKey; 18 /** SFTP 服务器地址IP地址*/ 19 private String host; 20 /** SFTP 端口*/ 21 private int port; 22 23 24 /** 25 * 构造基于密码认证的sftp对象 26 */ 27 public SFTPUtil(String username, String password, String host, int port) { 28 this.username = username; 29 this.password = password; 30 this.host = host; 31 this.port = port; 32 } 33 34 /** 35 * 构造基于秘钥认证的sftp对象 36 */ 37 public SFTPUtil(String username, String host, int port, String privateKey) { 38 this.username = username; 39 this.host = host; 40 this.port = port; 41 this.privateKey = privateKey; 42 } 43 44 public SFTPUtil(){} 45 46 /** 47 * 初始化ftp参数 48 * @param resultFileURL 49 */ 50 public SFTPUtil(String resultFileURL , String keys) throws Exception { 51 Map<String, String> map = URLUtil.parseSftp(resultFileURL); 52 init(map.get("ipAddress"),map.get("ipPort"),map.get("userName"),map.get("passWord"),keys); 53 log.info("ip: " map.get("ipAddress")); 54 log.info("port: " map.get("ipPort")); 55 log.info("userName: " map.get("userName")); 56 log.info("PassWord: " map.get("passWord")); 57 } 58 59 /**初始化参数**/ 60 private void init(String ip, String portN, String userName, String passWord,String keys) 61 throws Exception { 62 if(StringUtils.isNotEmpty(portN)){ 63 port=Integer.parseInt(portN); 64 }else{ 65 port = 21; 66 } 67 68 if(StringUtils.isNotEmpty(keys)){ 69 privateKey = keys; 70 } 71 72 host = new String(ip); 73 sftp = new ChannelSftp(); 74 username = new String(userName); 75 password = new String(passWord); 76 } 77 78 79 /** 80 * 连接sftp服务器 81 */ 82 public void login(){ 83 try { 84 JSch jsch = new JSch(); 85 if (privateKey != null) { 86 jsch.addIdentity(privateKey);// 设置私钥 87 } 88 89 session = jsch.getSession(username, host, port); 90 91 if (password != null) { 92 session.setPassword(password); 93 } 94 Properties config = new Properties(); 95 config.put("StrictHostKeyChecking", "no"); 96 97 session.setConfig(config); 98 session.connect(); 99 100 Channel channel = session.openChannel("sftp"); 101 channel.connect(); 102 103 sftp = (ChannelSftp) channel; 104 log.info("登陆 Sftp Server Success"); 105 } catch (JSchException e) { 106 e.printStackTrace(); 107 log.error(e.getMessage()); 108 } 109 } 110 111 /** 112 * 关闭连接 server 113 */ 114 public void logout(){ 115 if (sftp != null) { 116 if (sftp.isConnected()) { 117 sftp.disconnect(); 118 } 119 } 120 if (session != null) { 121 if (session.isConnected()) { 122 session.disconnect(); 123 } 124 } 125 } 126 127 /** 128 * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath directory 129 * @param basePath 服务器的基础路径 130 * @param directory 上传到该目录 131 * @param sftpFileName sftp端文件名 132 */ 133 public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{ 134 try { 135 sftp.cd(basePath); 136 sftp.cd(directory); 137 } catch (SftpException e) { 138 //目录不存在,则创建文件夹 139 String [] dirs=directory.split("/"); 140 String tempPath=basePath; 141 for(String dir:dirs){ 142 if(null== dir || "".equals(dir)) continue; 143 tempPath ="/" dir; 144 try{ 145 sftp.cd(tempPath); 146 }catch(SftpException ex){ 147 sftp.mkdir(tempPath); 148 sftp.cd(tempPath); 149 } 150 } 151 } 152 sftp.put(input, sftpFileName); //上传文件 153 } 154 155 156 /** 157 * 下载文件。 158 * @param directory 下载目录 159 * @param downloadFile 下载的文件 160 * @param saveFile 存在本地的路径 161 */ 162 public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException { 163 if (directory != null && !"".equals(directory)) { 164 sftp.cd(directory); 165 } 166 File file = new File(saveFile); 167 sftp.get(downloadFile, new FileOutputStream(file)); 168 } 169 170 /** 171 * 下载文件 172 * @param directory 下载目录 173 * @param downloadFile 下载的文件名 174 * @return 字节数组 175 */ 176 public byte[] download(String directory, String downloadFile) throws SftpException, IOException{ 177 if (directory != null && !"".equals(directory)) { 178 sftp.cd(directory); 179 } 180 InputStream is = sftp.get(downloadFile); 181 182 byte[] fileData = IOUtils.toByteArray(is); 183 184 return fileData; 185 } 186 187 188 /** 189 * 删除文件 190 * @param directory 要删除文件所在目录 191 * @param deleteFile 要删除的文件 192 */ 193 public void delete(String directory, String deleteFile) throws SftpException{ 194 sftp.cd(directory); 195 sftp.rm(deleteFile); 196 } 197 198 199 /** 200 * 列出目录下的文件 201 * @param directory 要列出的目录 202 */ 203 public Vector<?> listFiles(String directory) throws SftpException { 204 return sftp.ls(directory); 205 } 206 207 //上传文件测试 208 public static void main(String[] args) throws SftpException, IOException { 209 SFTPUtil sftp = new SFTPUtil("用户名", "密码", "ip地址", 22); 210 sftp.login(); 211 File file = new File("D:\\图片\\t0124dd095ceb042322.jpg"); 212 InputStream is = new FileInputStream(file); 213 214 sftp.upload("基础路径","文件路径", "test_sftp.jpg", is); 215 sftp.logout(); 216 } 217 218 /*** 219 * 获取ftp内容 220 * @param resultFileURL 221 * @return 222 */ 223 public String getFtpContent(String resultFileURL) { 224 String str=null; 225 log.info("SFTP getFtpContent Start"); 226 try { 227 Map<String, String> map = URLUtil.parseSftp(resultFileURL); 228 String ipAdress = map.get("ipAddress"); 229 int ipPort = SafeUtils.getInt(map.get("ipPort"),21); 230 String userName = map.get("userName"); 231 String passWord = map.get("passWord"); 232 log.info("sftp ipAdress=" ipAdress ",ipPort=" ipPort ",userName=" userName ",passWord=" passWord); 233 login(); 234 String path = map.get("path"); 235 path=path.replace("//","/"); //防止双杠导致目录失败 236 log.info("ftp path=" path); 237 238 /*String changePath = path.substring(0, path.lastIndexOf("/") 1); 239 log.info("ftp changePath=" changePath);*/ 240 241 InputStream inputStream = sftp.get(path); 242 243 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8")); 244 String data = null; 245 StringBuffer resultBuffer = new StringBuffer(); 246 while ((data = br.readLine()) != null) { 247 resultBuffer.append(data "\n"); 248 } 249 str = resultBuffer.toString(); 250 log.info("ftp content:" str); 251 logout(); 252 } catch (Exception e) { 253 // TODO Auto-generated catch block 254 e.printStackTrace(); 255 log.error("ftp error:",e); 256 } 257 return str; 258 } 259 } 2. 调用URLUtil.java 来帮助解析Url地址 1 public URLUtil class{ 2 /*** 3 * 用解析sftp 4 * @param url 5 * @return 6 * @throws Exception 7 */ 8 public static Map<String, String> parseSftp(String url) throws Exception{ 9 Map<String, String> temp = new HashMap<String, String>(); 10 String ipPort= "21"; 11 //由于 URL类解析 sftp地址会报错, 所以截取掉前面的s 12 url = url.substring(1); 13 URL urltemp = new URL(url); 14 String ipAddress = urltemp.getHost(); 15 if (urltemp.getPort()!=-1) { 16 ipPort = urltemp.getPort() ""; 17 }; 18 String path = urltemp.getPath(); 19 String userInfo = urltemp.getUserInfo(); 20 String userName = ""; 21 String userPwd = ""; 22 if(StringUtils.isNotEmpty(userInfo)){ 23 String[] array = userInfo.split(":"); 24 if(array.length>0){ 25 userName = array[0]; 26 } 27 28 if(array.length>=1){ 29 userPwd = array[1]; 30 } 31 } 32 temp.put("userName", userName); 33 temp.put("passWord", userPwd); 34 temp.put("ipAddress", ipAddress); 35 temp.put("ipPort", ipPort); 36 temp.put("path", path); 37 38 return temp; 39 } 40 }
3 代码中调用方法1 SFTPUtil sftpUtil = new SFTPUtil(resultFileURL,""); //初始化工具类, 第二个参数为密钥,没有就不填 2 cont = sftpUtil.getFtpContent(resultFileURL); //返回读取的string 字符串, 根据双方约定解析成不同格式即可 来源:https://www./content-1-663251.html |
|