java sftp 读取文件_Java代码获取SFTP服务器文件
与下游联调时遇到的问题, 一般我们会使用ftp来传递文件, 因为sftp的传输效率很低. 所以为了兼容,引用了网上的方法.
步骤
导入所需Jar包
编写工具类
代码中运用
1. 导入 Jsch-0.1.54.jar
直接去maven库中下载即可
2. 编写工具类--SFTPUtil.java
1 /**
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 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 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 parseSftp(String url) throws Exception{
9 Map temp = new HashMap();
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.icode9.com/content-1-663251.html
java sftp 读取文件_Java代码获取SFTP服务器文件相关推荐
- java获得sftp目录_Java代码获取SFTP服务器文件
1 /** 2 *@authorshansm3 * @date 2020/3/18 -17:274 */ 5 public classSFTPUtil {6 7 private transient L ...
- java opencv 读取视频_java使用OpenCV从视频文件中获取帧
本文实例为大家分享了java使用OpenCV从视频文件中获取帧的具体代码,供大家参考,具体内容如下 实现功能:使用Java获取mp4.mov.avi等视频文件中的图像帧,每秒获取一帧图像,并保存 环境 ...
- JAVA之旅(二十八)——File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤...
JAVA之旅(二十八)--File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤 我们可以继续了,今天说下File 一.File概述 文件的操作是非常 ...
- JAVA之旅(二十八)——File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤
JAVA之旅(二十八)--File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤 我们可以继续了,今天说下File 一.File概述 文件的操作是非常 ...
- java获取ftp服务器文件,java获取ftp服务器文件
java获取ftp服务器文件 [2021-02-05 07:26:23] 简介: php去除nbsp的方法:首先创建一个PHP代码示例文件:然后通过"preg_replace(" ...
- java excel转pdf linux,从JAVA直接读取EXCEL、WORD并生成PDF文件
从JAVA直接读取EXCEL.WORD并生成PDF文件 1.操作EXCEL和WORD文件 使用JAVA从EXCEL.WORD文件中读写数据,可以使用http://jexcelapi.sourcefor ...
- vb获取服务器文件路径,vb打开ftp服务器文件路径
vb打开ftp服务器文件路径 内容精选 换一换 该任务指导用户使用Loader将数据从HDFS/OBS导出到SFTP服务器.创建或获取该任务中创建Loader作业的业务用户和密码.确保用户已授权访问作 ...
- java 读取 指纹_java代码怎么获取数字的证书那一串20位指纹?
展开全部 通过JAVA来读取数字证书的方法获取20位指纹: CARead.java文件代码32313133353236313431303231363533e4b893e5b19e31333339663 ...
- linssh2 sftp读取远端目录,获取远端文件或者目录信息
环境信息 rhel65 libssh2版本:libssh2-1.8.2 libssh2目前遇到几个注意事项: 读取远端目录时,实体的名称没有存储在LIBSSH2_SFTP_ATTRIBUTES中(具体 ...
- java获取word图片_java代码获取word文件中的图片
1:需求 在线打开word文件后,用户插入图片.然后保存图片到服务器 2:方案 用pageoffice 在线打开文档的功能和提交数据的功能实现 3:核心代码 4:实现过程 (1)因为要获取数据区域的数 ...
最新文章
- 【数据库】兴唐第二十七节课之jdbc的使用
- 25.怎样在IDEA中使用JUnit4和JUnitGenerator V2.0自动生成测试模块
- 2016.9.9《Oracle查询优化改写技巧与案例》电子工业出版社一书中的技巧
- Mac下Homebrew的图形化界面工具Cakebrew
- JAVA NIO概述(一):I/O模型
- 创建一个framework
- c#中去掉字符串空格方法
- Fedora/Redhat 在线安装更新软件包,yum 篇 ── 给新手指南 (转载)
- mvp最小可行产品_我们如何打造最低可行产品(MVP)
- 95-134-116-源码-维表-kafka维表关联:广播方式
- IDEA中引入Bootstrap并展示第一个模板
- WinServer 2012 R2 搭建域控服务器、文件服务器并配置权限
- Keil——导出代码的PDF文件
- 微信小程序开发之组件view,scroll-view,swiper,text,rich-text,button,image,navigator
- pr EN2824 - Pr EN 2825- Pr EN 2826 是烟密度和烟气成分分析测试
- Vmware虚拟机ikuai路由配置
- 单片机:按键调节时钟
- 如何安装 Manjaro 21 桌面系统 ?
- php 文件预览 水印,PHP图片上传,预览图上传,水印设置
- Empress .... 概念