服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java使用Sftp和Ftp实现对文件的上传和下载

Java使用Sftp和Ftp实现对文件的上传和下载

2021-08-30 10:37天不生我落雨 Java教程

这篇文章主要介绍了Java使用Sftp和Ftp实现对文件的上传和下载,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

sftp和ftp两种方式区别,还不清楚的,请自行百度查询,此处不多赘述。完整代码地址在结尾!!

第一步,导入maven依赖

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- FTP依赖包 -->
<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.6</version>
</dependency>
<!-- SFTP依赖包 -->
<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.55</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

第二步,创建并编写SftpUtils类,运行main方法查看效果,如下

?
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
 
/**
 * @Description: sftp上传下载工具类
 * @Author: jinhaoxun
 * @Date: 2020/1/16 16:13
 * @Version: 1.0.0
 */
@Slf4j
public class SftpUtils {
 
  public static void main(String[] args) throws Exception {
    log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 1
    File file = new File("E:\\2.xlsx");
    InputStream inputStream = new FileInputStream(file);
    SftpUtils.uploadFile("", "", "", 22, "/usr/local",
        "/testfile/", "test.xlsx", null, inputStream);
 
    // 2
    SftpUtils.downloadFile("", "", "", 22,null,
        "/usr/local/testfile/", "test.csv","/Users/ao/Desktop/test.csv");
 
    // 3
    SftpUtils.deleteFile("", "", "", 22,null,
        "/usr/local/testfile/", "test.xlsx");
 
    // 4
    Vector<?> fileList = SftpUtils.getFileList("", "", "",
        22, null,"/usr/local/testfile/");
    log.info(fileList.toString());
    log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 下载文件
   * @param userName 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param basePath 根路径
   * @param filePath 文件路径(加上根路径)
   * @param filename 文件名
   * @param privateKey 秘钥
   * @param input 文件流
   * @Date: 2020/1/16 21:23
   * @Return: void
   * @Throws: Exception
   */
  public static void uploadFile(String userName, String password, String host, int port, String basePath,
                   String filePath, String filename, String privateKey, InputStream input) throws Exception {
 
    Session session = null;
    ChannelSftp sftp = null;
    // 连接sftp服务器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 设置私钥
        jsch.addIdentity(privateKey);
      }
 
      session = jsch.getSession(userName, host, port);
 
      if (password != null) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
 
      session.setConfig(config);
      session.connect();
 
      Channel channel = session.openChannel("sftp");
      channel.connect();
 
      sftp = (ChannelSftp) channel;
    } catch (JSchException e) {
      e.printStackTrace();
    }
    // 将输入流的数据上传到sftp作为文件
    try {
      sftp.cd(basePath);
      sftp.cd(filePath);
    } catch (SftpException e) {
      //目录不存在,则创建文件夹
      String [] dirs=filePath.split("/");
      String tempPath=basePath;
      for(String dir:dirs){
        if(null== dir || "".equals(dir)){
          continue;
        }
        tempPath+="/"+dir;
        try{
          sftp.cd(tempPath);
        }catch(SftpException ex){
          sftp.mkdir(tempPath);
          sftp.cd(tempPath);
        }
      }
    }
    //上传文件
    sftp.put(input, filename);
    //关闭连接 server
    if (sftp != null) {
      if (sftp.isConnected()) {
        sftp.disconnect();
      }
    }
    //关闭连接 server
    if (session != null) {
      if (session.isConnected()) {
        session.disconnect();
      }
    }
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 下载文件
   * @param userName 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privateKey 秘钥
   * @param directory 文件路径
   * @param downloadFile 文件名
   * @param saveFile 存在本地的路径
   * @Date: 2020/1/16 21:22
   * @Return: void
   * @Throws: Exception
   */
  public static void downloadFile(String userName, String password, String host, int port, String privateKey, String directory,
                String downloadFile, String saveFile) throws Exception{
    Session session = null;
    ChannelSftp sftp = null;
    // 连接sftp服务器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 设置私钥
        jsch.addIdentity(privateKey);
      }
 
      session = jsch.getSession(userName, host, port);
 
      if (password != null) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
 
      session.setConfig(config);
      session.connect();
 
      Channel channel = session.openChannel("sftp");
      channel.connect();
 
      sftp = (ChannelSftp) channel;
    } catch (JSchException e) {
      e.printStackTrace();
    }
    if (directory != null && !"".equals(directory)) {
      sftp.cd(directory);
    }
    File file = new File(saveFile);
    sftp.get(downloadFile, new FileOutputStream(file));
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 下载文件
   * @param userName 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privateKey 秘钥
   * @param directory 文件路径
   * @param downloadFile 文件名
   * @Date: 2020/1/16 21:21
   * @Return: byte[]
   * @Throws: Exception
   */
  public static byte[] downloadFile(String userName, String password, String host, int port, String privateKey,
                 String directory, String downloadFile) throws Exception{
    Session session = null;
    ChannelSftp sftp = null;
    // 连接sftp服务器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 设置私钥
        jsch.addIdentity(privateKey);
      }
 
      session = jsch.getSession(userName, host, port);
 
      if (password != null) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
 
      session.setConfig(config);
      session.connect();
 
      Channel channel = session.openChannel("sftp");
      channel.connect();
 
      sftp = (ChannelSftp) channel;
    } catch (JSchException e) {
      e.printStackTrace();
    }
    if (directory != null && !"".equals(directory)) {
      sftp.cd(directory);
    }
    InputStream is = sftp.get(downloadFile);
    byte[] fileData = IOUtils.toByteArray(is);
    return fileData;
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 删除文件
   * @param userName 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privateKey 秘钥
   * @param directory 文件路径
   * @param deleteFile 文件名
   * @Date: 2020/1/16 21:24
   * @Return: void
   * @Throws: Exception
   */
  public static void deleteFile(String userName, String password, String host, int port, String privateKey,
               String directory, String deleteFile) throws Exception{
    Session session = null;
    ChannelSftp sftp = null;
    // 连接sftp服务器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 设置私钥
        jsch.addIdentity(privateKey);
      }
 
      session = jsch.getSession(userName, host, port);
 
      if (password != null) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
 
      session.setConfig(config);
      session.connect();
 
      Channel channel = session.openChannel("sftp");
      channel.connect();
 
      sftp = (ChannelSftp) channel;
    } catch (JSchException e) {
      e.printStackTrace();
    }
    sftp.cd(directory);
    sftp.rm(deleteFile);
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 列出目录下的文件
   * @param userName 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privateKey 秘钥
   * @param directory 要列出的目录
   * @Date: 2020/1/16 21:25
   * @Return: java.util.Vector<?>
   * @Throws: Exception
   */
  public static Vector<?> getFileList(String userName, String password, String host, int port, String privateKey,
                   String directory) throws Exception {
    Session session = null;
    ChannelSftp sftp = null;
    // 连接sftp服务器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 设置私钥
        jsch.addIdentity(privateKey);
      }
 
      session = jsch.getSession(userName, host, port);
 
      if (password != null) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
 
      session.setConfig(config);
      session.connect();
 
      Channel channel = session.openChannel("sftp");
      channel.connect();
 
      sftp = (ChannelSftp) channel;
    } catch (JSchException e) {
      e.printStackTrace();
    }
    return sftp.ls(directory);
  }
 
}

第三步,创建并编写FtpUtils类,运行main方法查看效果,如下

?
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
 
import java.io.*;
 
/**
 * @Description: ftp上传下载工具类
 * @Author: jinhaoxun
 * @Date: 2020/1/16 15:46
 * @Version: 1.0.0
 */
@Slf4j
public class FtpUtils {
 
  public static void main(String[] args) throws Exception {
    log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 1
    File file = new File("E:\\2.xlsx");
    InputStream inputStream = new FileInputStream(file);
    FtpUtils.uploadFile("", 21, "", "", "/usr/local",
        "/testfile/", "test.xlsx", inputStream);
 
    // 2
    FtpUtils.downloadFile("", 21, "", "","/usr/local/testfile/",
        "test.csv", "/Users/ao/Desktop/test.csv");
    log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 向FTP服务器上传文件
   * @param host FTP服务器hostname
   * @param port FTP服务器端口
   * @param userName FTP登录账号
   * @param password FTP登录密码
   * @param basePath FTP服务器基础目录
   * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
   * @param filename 上传到FTP服务器上的文件名
   * @param input 本地要上传的文件的 输入流
   * @Date: 2020/1/16 19:31
   * @Return: boolean
   * @Throws: Exception
   */
  public static boolean uploadFile(String host, int port, String userName, String password, String basePath,
                   String filePath, String filename, InputStream input) throws Exception{
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
      int reply;
      // 连接FTP服务器
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
      // 登录
      ftp.login(userName, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      //切换到上传目录
      if (!ftp.changeWorkingDirectory(basePath+filePath)) {
        //如果目录不存在创建目录
        String[] dirs = filePath.split("/");
        String tempPath = basePath;
        for (String dir : dirs) {
          if (null == dir || "".equals(dir)){
            continue;
          }
          tempPath += "/" + dir;
          if (!ftp.changeWorkingDirectory(tempPath)) {
            if (!ftp.makeDirectory(tempPath)) {
              return result;
            } else {
              ftp.changeWorkingDirectory(tempPath);
            }
          }
        }
      }
      //设置上传文件的类型为二进制类型
      ftp.setFileType(FTP.BINARY_FILE_TYPE);
      //上传文件
      if (!ftp.storeFile(filename, input)) {
        return result;
      }
      input.close();
      ftp.logout();
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return result;
  }
 
  /**
   * @Author: jinhaoxun
   * @Description: 从FTP服务器下载文件
   * @param host FTP服务器hostname
   * @param port FTP服务器端口
   * @param userName FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径
   * @param fileName 要下载的文件名
   * @param localPath 下载后保存到本地的路径
   * @Date: 2020/1/16 19:34
   * @Return: boolean
   * @Throws: Exception
   */
  public static boolean downloadFile(String host, int port, String userName, String password, String remotePath,
                    String fileName, String localPath) throws Exception {
 
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
      int reply;
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
      // 登录
      ftp.login(userName, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      // 转移到FTP服务器目录
      ftp.changeWorkingDirectory(remotePath);
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {
          java.io.File localFile = new File(localPath + "/" + ff.getName());
 
          OutputStream is = new FileOutputStream(localFile);
          ftp.retrieveFile(ff.getName(), is);
          is.close();
        }
      }
      ftp.logout();
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return result;
  
}

完整代码地址:https://github.com/luoyusoft/java-demo
注:此工程包含多个包,FtpUtils代码均在com.luoyu.java.ftp包下
注:此工程包含多个包,SftpUtils代码均在com.luoyu.java.sftp包下

到此这篇关于Java使用Sftp和Ftp实现对文件的上传和下载的文章就介绍到这了,更多相关Java使用Sftp和Ftp文件上传和下载内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家! 

原文链接:https://www.jianshu.com/p/79dae0e59d29

延伸 · 阅读

精彩推荐