java sftp 读取文件_Java代码获取SFTP服务器文件

Java SFTP 文件操作指南
本文介绍了如何使用Java通过SFTP协议连接并操作远程文件。主要内容包括导入Jsch库,创建SFTPUtil工具类,提供基于密码和秘钥的认证方式,实现连接、上传、下载、删除文件以及获取文件内容的方法。
部署运行你感兴趣的模型镜像

与下游联调时遇到的问题, 一般我们会使用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

您可能感兴趣的与本文相关的镜像

EmotiVoice

EmotiVoice

AI应用

EmotiVoice是由网易有道AI算法团队开源的一块国产TTS语音合成引擎,支持中英文双语,包含2000多种不同的音色,以及特色的情感合成功能,支持合成包含快乐、兴奋、悲伤、愤怒等广泛情感的语音。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值